Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Powershell with progress bar is not writing results to a file, file remains blank

I'm trying to scan the network, and write the PC name of each corresponding ip to a text file. It was working, until I put the progress bar code in place. Now it will create the blank file, but never writes anything to it.

I was using Add-Content instead of Out-File, but that doesn't create the text file at all.

#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 
question from:https://stackoverflow.com/questions/65835022/powershell-with-progress-bar-is-not-writing-results-to-a-file-file-remains-blan

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A resonable formatting would have helped you (and others) to understand your code much easier:

#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 does not generate any ouptut. So it does not make sense to pipe it to any other cmdlet. If you really want to have 2 different and unrelated commands on one line you should separate them with a semikolon like Thomas already mentioned in the comments above.

That's the same for Start-Sleep by the way. I'd recommend to always read the complete help for the cmdlets you're about to use to learn how to use them.

To make your code easier to read you should use line breaks and indentation. Here is some more to read about: The PowerShell Best Practices and Style Guide


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...