此解决方案创建一个 psobject 并将每个对象添加到一个数组中,然后通过 Export-CSV 管道传输数组内容来创建 csv。
$results = @()
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation
如果将字符串对象通过管道传输到 csv,您会将其长度写入 csv,这是因为这些是字符串的属性,请参阅here http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/23/use-powershell-to-work-with-csv-formatted-text.aspx了解更多信息。
这就是为什么我首先创建一个新对象。
请尝试以下操作:
write-output "test" | convertto-csv -NoTypeInformation
这会给你:
"Length"
"4"
如果您在 Write-Output 上使用 Get-Member,如下所示:
write-output "test" | Get-Member -MemberType Property
你会看到它有一个属性 - 'length':
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property System.Int32 Length {get;}
这就是为什么Length将写入 csv 文件。
更新:附加 CSV如果文件变大,这不是最有效的方法......
$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
$results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{
foreach ($file in $REMOVE) {
Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"
}
} else {
$details = @{
Date = get-date
ComputerName = $Computer
Destination = $Destination
}
$results += New-Object PSObject -Property $details
}
}
$results | export-csv -Path $csvFileName -NoTypeInformation