Powershell - 通过远程连接出现 WMI 错误

Powershell - WMI error via remote connection

我在 powershell 中编写脚本,scrips 收集有关某些系统服务状态的信息,例如远程主机上的 DHCP 服务。有时连接到远程主机和从 WMI 收集信息时会出现问题。 下面的 WMI 命令:

$DHCP = Get-WmiObject win32_service -ComputerName $server 2>>$logerror2 | 
Where-Object -FilterScript {$_.Name -eq "dhcp"} 

我创建了具有两个属性的对象:

              [pscustomobject][ordered]@{
              ServerName = $server
              DHCP = $DHCP.State
              }

输出定向到 .csv 文件,文件内容如下所示:

"ServerName","DHCP"
"srv1","Running"
"srv2",,
"srv3",,

在名为 "srv2" 和 "srv3" 的主机上,连接和从远程主机 WMI 收集信息时出现问题。我想代替空白 space 提供一些信息,例如 "WMI Problem",文件的内容应如下所示:

"ServerName","DHCP"
"srv1","Running"
"srv2",WMI Problem,
"srv3",WMI Problem,    

试试这个,应该没问题:

## Clear the Error variable incase the last server had an error ##
if ($error)
{
    $error.clear()
}

## Attempt to do the WMI command ##
try
{
    $DHCP = Get-WmiObject win32_service -ComputerName $server -erroraction stop | Where-Object {$_.Name -eq "dhcp"}
}
Catch
{
    $errormsg = $_.Exception.Message
}

## If the WMI command errored then do this ##
if ($error)
{
    [pscustomobject][ordered]@{
    ServerName = $server
    DHCP = $errormsg
    }
}

## If the WMI command was successful do this ##
Else
{
    [pscustomobject][ordered]@{
    ServerName = $server
    DHCP = $DHCP.State
    }
}

借鉴@Dizzy 的回答。

$CSV = Foreach ($Server in $ServerList)
{
    $ServerObj = [pscustomobject][ordered]@{
        ServerName = $server
        DHCP = $null
    }

    ## Attempt to do the WMI command ##
    try
    {
        $DHCP = Get-WmiObject win32_service -ComputerName $server -erroraction stop | Where-Object {$_.Name -eq "dhcp"}
        [String]$ServerObj.DHCP = $DHCP.State
    }
    Catch
    {
        $errormsg = $_.Exception.Message
        [String]$ServerObj.DHCP = $errormsg
    }
    $ServerObj
}
$CSV | Export-Csv .\result.csv -NoTypeInformation