powershell - 带有进度条的 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
解决方案
合理的格式可以帮助您(和其他人)更轻松地理解您的代码:
#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 最佳实践和样式指南
推荐阅读
- python - 动态搜索列表中匹配条件的值
- c++ - 是比特集吗?仅当编写为 Oneliner 时,函数才返回错误结果
- asp.net - ASP.NET MVC 5 - 没有智能感知 .cshtml 文件
- angular - 从服务绑定属性到组件Angular 4
- perl - 将我的输出拆分为多个文件
- google-bigquery - 无法在没有可用于分区消除的过滤器的情况下查询表
- python - Python从txt文件中提取数据并忽略标题
- python - 对组应用操作
- node.js - 用于 Express 的 HTTP2 推送
- c# - 打开存储在 SQL Server 中的 Word 文件