如何使用PowerShell测试远程计算机的连接?
要使用PowerShell测试远程连接,请使用Test-Connection命令。PowerShell还支持Ping命令,并且两个命令几乎产生相同的输出,但Test-Connectioncmdlet支持高级参数。查看两个命令输出的外观。
ping命令 -
PS C:\Temp> ping Test1-Win2k16 Pinging Test1-Win2k16 [192.168.0.108] with 32 bytes of data: Reply from 192.168.0.108: bytes=32 time<1ms TTL=128 Reply from 192.168.0.108: bytes=32 time=1ms TTL=128 Reply from 192.168.0.108: bytes=32 time=1ms TTL=128 Reply from 192.168.0.108: bytes=32 time=1ms TTL=128 Ping statistics for 192.168.0.108: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 1ms, Average = 0ms
测试连接命令输出-
PS C:\Scripts> Test-Connection Test1-win2k16 Source Destination IPV4Address IPV6Address ------ ----------- ----------- ----------- ADDC Test1-win2k16 192.168.0.108 ADDC Test1-win2k16 192.168.0.108 ADDC Test1-win2k16 192.168.0.108 ADDC Test1-win2k16 192.168.0.108
您可以使用-Count参数减少检查次数。它与ping命令中的-n相似。
例
PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2 Source Destination IPV4Address IPV6Address ------ ----------- ----------- ----------- ADDC Test1-win2k16 192.168.0.108 ADDC Test1-win2k16 192.168.0.108
如果您需要安静地执行上述命令,则可以使用-Quiet参数,如果连接成功或失败,则该参数将给出布尔值(True或False)。
PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2 -Quiet True
Test-Connection的优点是它支持常见的参数,例如处理错误。在以下示例中,Any-Comp服务器不存在。为了在服务器不可访问或服务器名称不存在时捕获错误,我们将使用cmdlet支持的ErrorAction参数。
try { Test-Connection Any-Comp -Count 2 -ErrorAction Stop } catch { $_.Exception.Message }
输出结果
Testing connection to computer 'Any-Comp' failed: Cannot resolve the target name.