powershell - 需要帮助将 ping 结果写入分离文件以供上下机器使用
问题描述
我需要 ping 一个机器列表,并将结果分成上下两个不同的 .txt 文件。
$PingPCs = Get-Content "C:\Temp\Cache Cleanup Project\Computerlist.txt
foreach ($PC in $PingPCs) {
$up = Test-Connection $PC -Count 1 -Quiet
if($up) {
$Response = Test-Connection $PC -Count 1 | Select-Object Name
$Response ## Need help figuring out the outfile process to write to .txt ##
}
else {
$Failed = "$PC is not reachable"
$Failed ### Need help figuring out the outfile process to write to .txt ###
}
}
我需要帮助的两个地方只是将结果写入单独的文本文件。一个名为 Online.txt 的文件和另一个名为 Offline.txt 的文件。
解决方案
您可以这样做,而不是在每次迭代中导出结果并附加到文件中,最好先执行测试并将结果保存在内存中。全部完成后,导出结果:
$PingPCs = Get-Content "C:\Temp\Cache Cleanup Project\Computerlist.txt"
$result = foreach ($PC in $PingPCs)
{
$testConnection = Test-Connection $PC -Count 1 -Quiet
[pscustomobject]@{
ComputerName = $PC
TestConnection = $testConnection
}
}
$result.where({$_.TestConnection}) | Out-File "x:\path\to\online.txt"
$result.where({-not $_.TestConnection}) | Out-File "x:\path\to\offline.txt"
编辑
添加很好的优化以导出结果。谢谢@mklement0
$online, $offline = $result.where({$_.TestConnection},'Split')
$online | Out-File "x:\path\to\online.txt"
$offline | Out-File "x:\path\to\offline.txt"
推荐阅读
- javascript - 用悬停信息反应显示块
- c++ - 模板、静态和 dll
- c - C - 循环通过 void* 知道元素大小
- vba - 在 Macos 上运行 marco 时下标超出范围
- javascript - firebase 存储,将图像检索到 vue 应用程序
- dart - NetworkImage 和 Image.network 的区别?
- android - 在 Visual Studio 中新创建的 Android 虚拟设备不起作用
- android - ViewActions.click() 和只执行 view.performClick() 的自定义 ViewAction 有什么区别?
- java - Hibernate:来自本机查询的 BigInteger vs Long 用于 JPQL 查询
- python - 对值'z'的tensorflow feed_dict问题感到困惑而不是feed