使用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写主机和创建自定义对象,因此我这里不会详细介绍。