连接失败时,Powershell将Get Service重定向到stderr



之后:

$services = Get-Service -ComputerName $server 2>$null

stderr不会重定向到$null,当连接失败或权限不足时,会打印错误消息。

使用try/catch语句捕获(并抑制(异常:

try {
$services = Get-Service -ComputerName $server -ErrorAction Stop
# do stuff with $services here
}
catch [InvalidOperationException] {
# we'll ignore these
}

最新更新