【问题标题】:Dont output any duplicate values to a csv file不要将任何重复值输出到 csv 文件
【发布时间】:2020-03-01 00:06:08
【问题描述】:

我正在将 json 文件转换为 csv 文件。我在我的 csv 文件中输出四列,但我不想输出任何重复的值。

我将变量添加到数组并将它们输出到 csv 文件,如果“名称”列中有任何重复值,因此如果发生重复,则不要将其添加到输出中。我真的不知道该怎么做。

 ForEach ($fileEnvironment in $jsonVariables.ScopeValues.Environments) { 
        #Create empty array
        $dataArray = @()

      ForEach ($fileVariable in $jsonVariables.Variables) {
         if($fileVariable.Description -eq $null) {
            $fileVariable.Description = 'No Description'
        }
            if (!!$fileVariable.Scope) {
                if (!!$fileVariable.Scope.Environment) {
                    if ($fileEnvironment.Id -eq $fileVariable.Scope.Environment[0]) {                   
                        #Add fileVariable to the array
                        $dataArray += $fileVariable

                    } 
                }
            }
        }

  $filename="$($outputPath)\$($projectName)_$($fileEnvironment.Name).csv"
            if ($dataArray.Count -ne 0) {
                 $dataArray | Select-Object -Property 
  Name,Type,Value,Description | Export-Csv -NoTypeInformation -Path 
  $fileName
        }            

我不希望 Name 列有重复的值,这样您就可以看到 apiconfig 重复了,我只想将一个 apiconfig 输出到 csv。在 csv 文件中输出如下: 名称 类型 值 描述 apiConfig String ... 无 描述 apiconfig String ... 无说明

【问题讨论】:

    标签: json powershell csv


    【解决方案1】:

    您可以使用HashSet 过滤掉重复项。

    这是一个说明这个想法的控制台日志。

    $listWithDuplicates = @([PSCustomObject]@{Name="A";Desc="1"},[PSCustomObject]@{Name="A";Desc="2"},[PSCustomObject]@{Name="B";Desc="3"})
    
    ▷ $listWithDuplicates
    
    Name Desc
    ---- ----
    A    1
    A    2
    B    3
    
    ▷ $set = New-Object "System.Collections.Generic.HashSet[string]"
    ▷ $listWithoutDuplicates = $listWithDuplicates  |? {$set.Add($_.Name)}
    ▷ $listWithoutDuplicates
    
    Name Desc
    ---- ----
    A    1
    B    3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2017-08-19
      • 2018-03-25
      • 1970-01-01
      • 2013-02-22
      • 2021-10-24
      相关资源
      最近更新 更多