【问题标题】:pipe foreach loop CSV PowerShell管道 foreach 循环 CSV PowerShell
【发布时间】:2013-11-28 22:51:55
【问题描述】:

我编写了一个脚本,但无法将其导出为 CSV 或以任何方式输出。

PowerShell 不喜欢 foreach 循环和导出。

对于 .txt 文件中的每个“文件夹路径/文件名”,它会检查文件是否仍然存在并输出 true 或 false + 文件夹路径/文件名。

脚本工作正常,只是无法将内容导出为 CSV。

任何想法我做错了什么?

foreach ($WantFile in Get-Content "C:\scripts\folderpaths.txt") {
    $FileExists = Test-Path $WantFile

    if ($FileExists -eq $True) {
        Write-Output $wantfile "True"
    } else {
        Write-Output $wantfile "False"
    }
} | Export-Csv C:\scripts\output.csv -noType 

【问题讨论】:

  • 您要写入输出文件的内容是什么?您的循环不会向管道写入任何内容。
  • @alroc AFAICS 这正是他试图解决的问题。 ;)
  • 对,但是他还没有定义output.csv的预期内容。如果不知道目的地,就无法很好地规划路线。
  • @alroc 从Write-Output 的说明来看,我怀疑他想要一个包含 2 列的 CSV:一列用于文件名,一列用于布尔值。
  • 很好,我摆脱了“If Else 语句”,只使用了 $FileExists 变量的 True、False 输出。成功了吗:) 干杯

标签: powershell csv pipe


【解决方案1】:

将您的代码更改为:

Get-Content 'C:\scripts\folderpaths.txt' | % {
  if (Test-Path -LiteralPath $_) {
    Write-Output $_ "True"
  } else {
    Write-Output $_ "False"
  }
} | Export-Csv 'C:\scripts\output.csv' -NoType 

不过,我怀疑生成的文件是否包含您所期望的内容。 Export-Csv 导出对象的属性。您生成的输出是字符串对象(实际上,每个 Write-Output 语句都有 2 个),它们的唯一属性是 Length,因此您的结果将是一列,其中包含您回显的字符串的长度。

要创建具有 2 列的 CSV,一列用于路径,另一列用于存在路径,您需要创建具有所需属性的对象,例如像这样:

Get-Content 'C:\scripts\folderpaths.txt' `
  | select @{n='Path';e={$_}}, @{n='Exists';e={Test-Path -LiteralPath $_}} `
  | Export-Csv 'C:\scripts\output.csv' -NoType

【讨论】:

  • 非常感谢!!第二个代码是解决方案,并准确地输出我希望的方式:)
  • 虽然在我的原始代码中,我如何将输出(例如真或假)输出到变量中?
  • @user2770724 我不确定你的意思。您希望变量中的哪个输出?
【解决方案2】:

关于原始问题(将 foreach 循环的输出导出到 CSV),您可以通过将其包装在子表达式中来将其输出到管道,但这并不能解决脚本中的其他问题到您要导出的内容:

$(ForEach ($WantFile in Get-Content "C:\scripts\folderpaths.txt"){

  $FileExists = Test-Path $WantFile 

  If ($FileExists -eq $True) {Write-Output $wantfile "True"}

  Else {Write-Output $wantfile "False"}

})| export-csv C:\scripts\output.csv -noType 

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,我通过以下方式解决了问题。

    $forloop = foreach ( $i in $computers)
        {
          $i
          $out = .\psexec.exe \\$i C:\hp\hpsmh\bin\smhlogreader.exe --version 
          $out
    
    
         } 
    
    $forloop | Out-file C:\scripts\output.txt -Append
    

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 1970-01-01
      • 2017-10-10
      • 2021-11-09
      • 2016-07-11
      • 2011-04-29
      • 2011-12-06
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多