Techibee.com

Handling WMI errors in PowerShell

Today I worked on writing a script and in that I got a requirement to suppress errors. At the same time, I want to log the error description for my referrence. To achieve this, I made use of two parameters of Get-WmiObject cmdlet. They are, -ErrorVariable and -ErrorAction

In brief, the argument passed to -ErrorVariable stores the details of the error generated and -ErrorAction specifies what to do incase of errors, like whether to continue execution or stop or whatever action. Google search will make you to land in few beautiful sites which has more info about these two parameters. Alternately, you can run “Get-Help about_commonparameters”

OK, now lets see how we can suppress and capture the errors from WMI execution. Below command runs against a computer which doesn’t exists. I don’t want my script to fail there and it should continue by logging the error somewhere.

Get-WmiObject -Class Win32_Product -ComputerName nonexists -ErrorVariable myerror -ErrorAction SilentlyContinue

Above command will fail in real, but it will not show any error in screen. Error will be saved in $myerror object. To see the error, issue below command

$myerror[0].exception

To clear the error from object, use below

$myerror.clear()

To see how many errors are stored in this object, use below

$myerror.count
[/code]
You can use this in your scripts to avoid powershel printing errors in console and log to some file. Hope this helps.

Exit mobile version