一个更好的解决方案,它使用基于以下的端口测试:https ://theolddogscriptingblog.wordpress.com/2012/05/11/wmi-hangs-and-how-to-avoid-them/
这是那里找到的脚本的修改版本以及使用它的一种方式的示例:
function Test-Port {
<#
.SYNOPSIS
Tests connection to port 135 on the SQL server, so I guess it is confined to M$ servers
.DESCRIPTION
.PARAMETER server
computername or IP address
.PARAMETER port
port defaults to 135
.PARAMETER timeout
in milliseconds, defaults to 1000
.EXAMPLE
Test-Port myserver.com
#>
Param(
[string] $server,
$port=135,
$timeout=1000, # milliseconds
[switch]$verbose
)
# Does a TCP connection on specified port (135 by default)
# Create TCP Client https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx
$tcpclient = new-Object system.Net.Sockets.TcpClient
# Initiate an asynchronous request to machine on Port
$iar = $tcpclient.BeginConnect($server,$port,$null,$null)
# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
# Check to see if the connection is done
if(!$wait)
{
# Close the connection and report timeout
$tcpclient.Close()
if($verbose){Write-Host Connection Timeout }
Return $false
}
else
{
# Close the connection and report the error if there is one
$error.Clear()
$tcpclient.EndConnect($iar) | out-Null
if(!$?){if($verbose){write-host $error[0]};$failed = $true}
$tcpclient.Close()
}
# Return $true if connection Establish else $False
if($failed){
return $false
} else {
return $true
}
}
#Found from using for a similar purpose that checking port 49153 was more reliable than 135
# also the test-connection is unnecessary and that very small timeouts, e.g., 10ms, worked on our network, which really speeds things up but you should test what works on your network
#Use like this
$computername = "myserver.com"
if (Test-Port -srv $computername -port 49153 -timeout 10) {
# Slew of WMI commands go here.
} else {
Write-Warning "Could ping $computername but NOT reach RPC port`n so can't use it for WMI"
}