【问题标题】:Export-CSV only returns first elementExport-CSV 仅返回第一个元素
【发布时间】:2017-03-29 09:40:26
【问题描述】:

所以我有这个脚本,它从 xml 中获取数据,特别是机器的名称,然后是每个机器的 ID 号列表。我可以将每个变量都放入变量中,但是当我尝试列出所有 id 时,只有每个 id 的第一个元素出现。我认为 Export-CSV -Append 可以解决这个问题,但到目前为止什么都没有。

$path="C:\Users\Desktop\DataIDs"
$xmls = Get-ChildItem $path\* -Recurse | where {$_.Name -like '*DataIDX*'} 

$results = New-Object psobject

ForEach ($xml in $xmls) {
    [xml]$results = Get-Content $xml
    $Name = $results.Benchmark.TestResult.target
    $VID1 = @($results.Benchmark.TestResult.'rule-result' | where {$_.result -eq 'fail'}).Version | Sort-Object
    $VID = $VID1 | Out-String

    ForEach ($id in $VID) {
        $results | Add-Member -MemberType NoteProperty -Name $Name -Value $id
        }
}

$results | Export-Csv $path\results.csv -NoTypeInformation -Append
Remove-Variable results

【问题讨论】:

    标签: xml powershell foreach formatting export-to-csv


    【解决方案1】:

    好吧,你添加成员的方式完全放弃了:

    Add-Member -MemberType NoteProperty -Name $Name -Value $id
    

    您总是在附加同一个成员。因此,其他附加内容会抛出“该成员已经存在并且无法写入该属性”或类似的东西。

    ps。我的错,我没有正确阅读原始问题。我已经编辑了答案以正确解释它。

    【讨论】:

      【解决方案2】:

      您需要使用一个数组来存储所有$results 对象,您每次都在覆盖它...

      编辑:我看到的另一个问题是你的$VID 是一个字符串对象,你不能迭代一个字符串对象,你会得到字符......我相信这不是你需要的,删除Out-String,然后重试

      试试这个:

      $path="C:\Users\Desktop\DataIDs"
      $xmls = Get-ChildItem $path\* -Recurse | where {$_.Name -like '*DataIDX*'} 
      
      $resultsArray = @()
      ForEach ($xml in $xmls) {
          [xml]$results = Get-Content $xml
          $Name = $results.Benchmark.TestResult.target
          $VID1 = @($results.Benchmark.TestResult.'rule-result' | where {$_.result -eq 'fail'}).Version | Sort-Object
          $VID = $VID1 
      
          ForEach ($id in $VID) {
              $results | Add-Member -MemberType NoteProperty -Name $Name -Value $id
              }
      $resultsArray += $results
      }
      
      $resultsArray | Export-Csv $path\results.csv -NoTypeInformation -Append
      Remove-Variable results
      

      【讨论】:

      • 感谢您的快速休息,尝试了这个并且我得到“您不能在空值表达式上调用方法”但是您的说法听起来不错
      猜你喜欢
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2019-06-10
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      相关资源
      最近更新 更多