如果在多台带有 -Quiet 的计算机上使用测试连接,我如何知道哪个结果适用于哪台计算机? [英] If using Test-Connection on multiple computers with -Quiet how do I know which result is for which computer?
问题描述
如果在多台带有 -Quiet 的计算机上使用测试连接,我如何知道哪个结果适用于哪台计算机?
If using Test-Connection on multiple computers with -Quiet how do I know which result is for which computer?
例如
$computers = ("PC1","PC2","PC3")
$results = Test-Connection -ComputerName $computers -count 2 -quiet
编辑以显示我在下面的讨论中提出的观点
EDITED TO SHOW POINT I AM MAKING IN DISCUSSION BELOW
不使用 -quiet
$computers = ("PC1","PC2","PC3")
$results = Test-Connection -ComputerName $computers -count 2
PC3 没有响应所以出错
PC3 not responding so get error
Test-Connection : 测试连接到计算机PC3"失败:没有这样的主机在 line:3 char:16
Test-Connection : Testing connection to computer 'PC3' failed: No such host is known At line:3 char:16
$results 只包含那两台可以工作的计算机
And $results only contains those 2 computers which worked
如何让 $results 包含所有 3 台计算机的结果 - PC3 处于故障状态
How to get $results to contains results for all 3 computers - with status of failure for PC3
推荐答案
为了在结果中存储单个计算机的故障状态,我认为唯一的方法是在单个计算机上调用 Test-Connection
.这样您就可以检查每个 ping 的 $null
结果.
To store failure status for individual computers in the result, I think the only way is to call Test-Connection
with single computer. This way you can check for $null
result of each ping.
为了仍然并行运行查询,您可以使用 ForEach-Object -Parallel
,如下例所示.
In order to still run the queries in parallel, you could use ForEach-Object -Parallel
as in the following example.
$computers = 'localhost', '0.0.0.0', '127.0.0.1'
# Do one call to Test-Connection per computer, but still in parallel
$results = $computers | ForEach-Object -Parallel {
# $status will be $null on critical error
$status = Test-Connection -ComputerName $_ -count 2 -quiet
# This implicitly adds an object with Computer name and status to the output array $result
[PSCustomObject]@{
Computer = $_
Status = if( $null -ne $status ) { $status } else { 'Failure' }
}
}
# Sort the results on the computer index
$results | Sort-Object { $computers.IndexOf( $_.Computer ) }
输出:
Computer Status
-------- ------
localhost True
0.0.0.0 Failure
127.0.0.1 True
Sort-Object
调用存在是因为 $results
数组可以按任何顺序排列.这取决于计算机的响应速度.
The Sort-Object
call is there because the $results
array can be in any order. It depends on how fast the computers respond.
除了输出Failure"之外,您还可以输出错误详细信息.您可以通过 $Error[0]
获取最后一条错误记录.
Instead of outputting "Failure", you could also output error details. You could get the last error record through $Error[0]
.
这篇关于如果在多台带有 -Quiet 的计算机上使用测试连接,我如何知道哪个结果适用于哪台计算机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!