管道foreach循环CSV PowerShell [英] pipe foreach loop CSV PowerShell
问题描述
我已经编写了一个脚本,但是无法将其导出为CSV或以任何方式输出.
I've written a script but cannot get it to export to CSV or output in any way.
PowerShell不喜欢foreach
循环和导出.
PowerShell does not like foreach
loops and exporting.
对于.txt文件中的每个文件夹路径/文件名",它都会检查文件是否仍然存在,并输出true或false +文件夹路径/文件名.
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.
脚本工作正常,只是无法将其导出为CSV.
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
推荐答案
将代码更改为此:
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
,因此您的结果将是一列,其中包含您要回显的字符串的长度.
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.
要创建包含2列的CSV,一列用于路径,另一列用于路径的存在,您需要创建具有所需属性的对象,例如像这样:
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
这篇关于管道foreach循环CSV PowerShell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!