管foreach循环CSV的PowerShell(pipe foreach loop CSV Pow

2019-10-19 01:30发布

我写了一个脚本,但不能让它导出到CSV或输出以任何方式。

PowerShell不喜欢foreach循环和出口。

对于.txt文件每个“FOLDERPATH /文件名”,它会检查该文件是否仍然存在,输出真或假+ FOLDERPATH /文件名。

脚本工作正常,只是不能导出到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 

Answer 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出口对象的属性。 您生成的输出是String对象(2每Write-Output语句,实际上),他们唯一的财产是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


Answer 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 


Answer 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


文章来源: pipe foreach loop CSV PowerShell