带进度条的Powershell没有将结果写入文件,文件保持空白



我正在尝试扫描网络,并将每个对应ip的PC名写入文本文件。它一直在工作,直到我把进度条形码安装到位。现在它将创建一个空白文件,但不会向其中写入任何内容。

我使用的是Add-Content而不是Out-File,但这根本不会创建文本文件。

#Declare IP range
$range = 1..254
$address = “192.168.0.$_”
#status
Write-Output "Scanning active PCs"
#Scan ip range and get pc names
$range | ForEach-Object {Write-Progress “Scanning Network” $address -PercentComplete (($_/$range.Count)*100) | Start-Sleep -Milliseconds 100 | Get-WmiObject Win32_PingStatus -Filter "Address='192.168.0.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0 and ProtocolAddressResolved like '%.domain.com'"  | select -ExpandProperty ProtocolAddressResolved} | Out-File C:PowershellScriptsComputerList.txt 

合理的格式将帮助您(和其他人)更容易理解您的代码:

#Declare IP range
$range = 1..254
$address = "192.168.0."
#status
Write-Output "Scanning active PCs"
#Scan ip range and get pc names
$range | 
ForEach-Object { 
Write-Progress 'Scanning Network' $address$_ -PercentComplete (($_ / $range.Count) * 100) 
Start-Sleep -Milliseconds 100
Get-WmiObject Win32_PingStatus -Filter "Address='192.168.0.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0 and ProtocolAddressResolved like '%.domain.com'"  | 
Select-Object -ExpandProperty ProtocolAddressResolved 
} | 
Out-File C:PowershellScriptsComputerList.txt

Write-Output不生成任何输出。因此,将它管道到任何其他cmlet是没有意义的。如果你真的想在一行中有两个不同且不相关的命令,你应该像Thomas在上面的评论中提到的那样用分号把它们分开。

顺便说一下,Start-Sleep也是一样的。我建议总是阅读您将要使用的cmlet的完整帮助来学习如何使用它们。

为了让你的代码更容易阅读,你应该使用换行和缩进。PowerShell最佳实践和风格指南

最新更新