我用powershell编写了脚本,script收集一些系统服务的状态信息,例如远程主机上的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, 发布于 2017-10-02 16:06:14
试试这个,应该可以:
## 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-02 17:23:44
从@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 -NoTypeInformationhttps://stackoverflow.com/questions/46528432
复制相似问题