我有一个脚本,它应该在三个服务器上运行一个测试连接和一个测试网络连接,现在我正在使用"localhost“进行测试。
问题是我想让它至少做两次“测试连接”,但是输出是非常奇怪的(从逻辑的角度来看是合理的,但是从输出的角度看不是)。
下面是代码:如果我使用count参数并将其设置为1次,则输出是正确的,它显示了它进行测试的一台pc,如果我将其设置为2,则输出将出现混乱。
$computers="localhost"
foreach ($pc in $computers){
$test_connection = Test-Connection -ComputerName $pc -Count 2
$test_netconnection = Test-NetConnection $pc -Port 1433
#}else{ Write-Host "can't reach $pc"}
[pscustomobject] @{
LocalPC =$test_connection.PSComputerName
'Tested-Server' =$test_netconnection.ComputerName
Bytes =$test_connection.buffersize
Time =$test_connection.ResponseTime
RemotePort =$test_netconnection.RemotePort
TcpTestSucceeded =$test_netconnection.TcpTestSucceeded
}| ft -AutoSize #end of Customobject
}
#}#end of foreach loop
pause产出:
WARNING: TCP connect to (::1 : 1433) failed
WARNING: TCP connect to (127.0.0.1 : 1433) failed
LocalPC Tested-Server Bytes Time RemotePort TcpTestSucceeded
------- ------------- ----- ---- ---------- ----------------
{LEVL-01, LEVL-01} localhost {32, 32} {0, 0} 1433 False在第二个输出中,T也显示了奇怪的输出,我正在添加Erroraction参数(但我将把它留给另一个帖子),我如何将这些双本地-pc输出传输到一个输出中?
非常感谢你的帮助
发布于 2018-04-06 11:20:55
根据注释,您的问题是$test_connection最终包含两个对象,每个测试结果都包含一个对象。可以使用数组索引操作符(例如[0] )来选择特定对象的结果,也可以使用Select -First 1获得第一个结果。我推荐后者,因为如果结果碰巧为空,则不太可能引发异常。
作为进一步的建议,您可以使用Measure-Object -Average返回两个测试所需时间的平均结果。我还建议您不要在循环中使用Format-Table,而是将结果整理到变量中,然后在该变量上使用它。
下面是您的代码中的修订:
$computers="localhost"
$Result = foreach ($pc in $computers){
$test_connection = Test-Connection -ComputerName $pc -Count 2
$test_netconnection = Test-NetConnection $pc -Port 1433
[pscustomobject] @{
LocalPC = ($test_connection | Select -First 1).PSComputerName
'Tested-Server' = $test_netconnection.ComputerName
Bytes = ($test_connection | Select -First 1).Bytes
Time = ($test_connection | Measure-Object -Average ResponseTime).Average
RemotePort = $test_netconnection.RemotePort
TcpTestSucceeded = $test_netconnection.TcpTestSucceeded
}
}
$Result | Ft -AutoSize发布于 2018-04-06 11:13:36
这将为每次“ping”尝试创建一个单独的对象:
$computers="localhost"
foreach ($pc in $computers)
{
$test_netconnection = Test-NetConnection $pc -Port 1433
Test-Connection -ComputerName $pc -Count 2 |
ForEach-Object {
[pscustomobject] @{
LocalPC =$_.PSComputerName
'Tested-Server' =$test_netconnection.ComputerName
Bytes =$_.buffersize
Time =$_.ResponseTime
RemotePort =$test_netconnection.RemotePort
TcpTestSucceeded =$test_netconnection.TcpTestSucceeded
}
} | ft -AutoSize #end of Customobject
} https://stackoverflow.com/questions/49691088
复制相似问题