1

我如何在下面的脚本中添加一个捕获,以便它忽略不在线的机器?

目前,当机器不在线时,我收到以下错误消息:

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\fcheck\run.ps1:6 char:9
+     gwmi <<<<  win32_operatingsystem -computername $hostname | ForEach-Object {
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

到目前为止,这是我的代码:

$dict.Keys | foreach-object {
    $currKey = $_
    $dict[$_] | ForEach-Object {
        $PSObject = New-Object PSCustomObject | Select hostname, os, type
        $PSObject.hostname = $_
        $PSObject.os = Get-OS $_
        $PSObject.type = $currType
        $VMObjects += $PSObject
    }
}


$VMObjects | ft
4

2 回答 2

1

在尝试导致错误的操作之前,请检查计算机是否在线。

if (test-connection -computername $hostname -quiet -count 1) {
# Run your process
} else {
# Computer is offline, do we need to do something different?
}

Test-Connection在 PowerShell 2.0 及更高版本中可用。

于 2013-10-01T16:57:03.937 回答
0

使用Get-WmiObjectcmdlet 时,使用如下设置错误操作标志:

-ErrorAction SilentlyContinue

遇到它们时不会显示任何错误。

于 2013-10-01T14:08:04.047 回答