使用ForEach-Object而不是foreach(in)構造的流水線。使用ForEach-Object將運行命令作爲管道的一部分,這將允許您將輸出捕獲爲變量。
$PingMachines=import-Csv -path C:\temp\pcs.csv -Header cn,operatingsystem,LastLogonDate
$PingMachines.cn | ForEach-Object {
$PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$_'" | `
Select-Object StatusCode
If ($PingStatus.StatusCode -eq 0){
Write-Host $_ "up"
}
Else {
Write-Host $_ "down"
}
}
你能想到的管線版本的$ _自動變量是這樣的:
foreach($_ in $PingMachines.cn) {
#code that uses $_
}
一旦你有一個管道去,你需要輸出的對象,而不是隻打印到屏幕使用Write-主持人:
$PingMachines=import-Csv -path C:\temp\pcs.csv -Header cn,operatingsystem,LastLogonDate
$PingResults = $PingMachines.cn | ForEach-Object {
$PingStatus = Gwmi Win32_PingStatus -Filter "Address = '$_'" | `
Select-Object StatusCode,Address
#I added the Address property above so you would have the machine name in the output object
If ($PingStatus.StatusCode -eq 0){
Write-Host $_ "up"
}
Else {
Write-Host $_ "down"
}
#Send the $PingStatus object out on the pipeline, which will end up in $PingResults
Write-Output $PingStatus
}
月攪拌機最近發表了一篇很好的文章powershell.org覆蓋輸出對象VS寫主機和創建自定義對象,因此我這裏不會詳細介紹。