0

我在 powershell 中编写脚本,脚本收集有关某些系统服务状态的信息,例如远程主机上的 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 收集信息的问题。我想代替空格来提供一些信息,例如“WMI 问题”,文件的内容应如下所示:

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

2 回答 2

1

试试这个,应该没问题:

## 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
    }
}
于 2017-10-02T16:06:14.727 回答
0

从@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
于 2017-10-02T17:23:44.797 回答