首页 > 解决方案 > 带有进度条的 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:\PowershellScripts\ComputerList.txt 

标签: powershell

解决方案


合理的格式可以帮助您(和其他人)更轻松地理解您的代码:

#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:\PowershellScripts\ComputerList.txt

Write-Output不会产生任何输出。因此,将其通过管道传递给任何其他 cmdlet 是没有意义的。如果你真的想在一行中有 2 个不同且不相关的命令,你应该用分号分隔它们,就像上面评论中已经提到的 Thomas。

顺便说一下,Start-Sleep也是如此。我建议您始终阅读您将要使用的 cmdlet 的完整帮助,以了解如何使用它们。

为了使您的代码更易于阅读,您应该使用换行符和缩进。这里还有一些要阅读的内容:PowerShell 最佳实践和样式指南


推荐阅读