Reputation: 595
I wrote script in powershell, scrips collects info about status of some system services, for example DHCP service on remote hosts. Sometimes there is a problem with connection to the remote hosts and collect info from WMI. The WMI command below:
$DHCP = Get-WmiObject win32_service -ComputerName $server 2>>$logerror2 |
Where-Object -FilterScript {$_.Name -eq "dhcp"}
I created object with two properties:
[pscustomobject][ordered]@{
ServerName = $server
DHCP = $DHCP.State
}
The output is directed to the .csv file, content of the file looks like this:
"ServerName","DHCP"
"srv1","Running"
"srv2",,
"srv3",,
On hosts named "srv2" and "srv3" there is a problem with connection and gathering info from remote hosts WMI. I would like instead of blank space to give some info, for example "WMI Problem", and the content of the file should looks like this:
"ServerName","DHCP"
"srv1","Running"
"srv2",WMI Problem,
"srv3",WMI Problem,
Upvotes: 0
Views: 237
Reputation: 2676
Taking a page from @Dizzy's answer.
$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
Upvotes: 0
Reputation: 111
Try this, should be ok:
## 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
}
}
Upvotes: 1