问题
I've written a script but cannot get it to export to CSV or output in any way.
PowerShell does not like foreach
loops and exporting.
For each "folderpath/filename" in the .txt file it checks to see if the file is still there and outputs true or false + folderpath/file name.
Script works fine, just cannot get the thing to export to CSV.
Any ideas what I'm doing wrong?
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
回答1:
Change your code to this:
Get-Content 'C:\scripts\folderpaths.txt' | % {
if (Test-Path -LiteralPath $_) {
Write-Output $_ "True"
} else {
Write-Output $_ "False"
}
} | Export-Csv 'C:\scripts\output.csv' -NoType
I doubt that the resulting file will contain what you expect, though. Export-Csv
exports the properties of objects. The output you generate are string objects (2 with each Write-Output
statement, actually), and their only property is Length
, so your result will be one column with the lengths of the strings you echo.
To create a CSV with 2 columns, one for path and the other for existence of the path you need to create objects with the desired properties, e.g. like this:
Get-Content 'C:\scripts\folderpaths.txt' `
| select @{n='Path';e={$_}}, @{n='Exists';e={Test-Path -LiteralPath $_}} `
| Export-Csv 'C:\scripts\output.csv' -NoType
回答2:
With regard to the original question (exporting the output of a foreach loop to CSV), you can make that output to the pipeline by wrapping it in a subexpression, but that's not going to solve the other problems in your script with regard to what it is you're trying to export:
$(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:
I got the same problem and i got it worked by doing as follow.
$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
来源:https://stackoverflow.com/questions/20275871/pipe-foreach-loop-csv-powershell