1

I am having issues understanding the use of the try, catch statement.

I want to use it as a general error detection case so that is there are any issues in the given function the script will output "Server Offline"

The below snippet queries the WMI object on a server for it's list of HDD's and formats it into a table. If there server or WMI is not available I want to have "Server Offline" appended to the txt output file.

Currently the catch statement is never invoked when there is an error.

Can try catch be used this way?

try {
    Get-WmiObject Win32_LogicalDisk -ComputerName  $server   | ft $server,deviceid,@{Label="Size(GB)";Expression={($_.Size/ 1gb) -as [int]}},@{Label="FreeSpace(Mb)";Expression={($_.FreeSpace/1mb) -as [int]}} -auto  | Out-File  c:\temp\ServersHDDAudit_OUTPUT-$a-$b.txt -Append

}
catch {
    $server + ": Server Offline" | Out-File  c:\temp\ServersHDDAudit_OUTPUT-$a-$b.txt -Append 
}

Samuel

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Samuel Meddows
  • 36,162
  • 12
  • 38
  • 36

2 Answers2

3

You'll find the information in one of my other post here, but when you write a CmdLet in PowerShell you can decide to throw exception or manage the error. Get-WmiObject manage the errors so it writes the error and return a value. You can ask it to "silently continue" and throw your own exception.

try
{
  $ld = Get-WmiObject Win32_LogicalDisk -ComputerName  $server -ErrorAction SilentlyContinue
  if ($ld -ne $null)
  {
    $ld | ft $server,deviceid,@{Label="Size(GB)";Expression={($_.Size/ 1gb) -as [int]}},@{Label="FreeSpace(Mb)";Expression={($_.FreeSpace/1mb) -as [int]}} -auto  | Out-File  c:\temp\ServersHDDAudit_OUTPUT-$a-$b.txt -Append
  }
  else
  {
    throw $Error[0].exception.Message
  }
}
catch
{
  $server + ": $_" | Out-File  c:\temp\ServersHDDAudit_OUTPUT-$a-$b.txt -Append 
}

Remark : you can set -ErrorAction Stop parameter to have a exception thrown by Get-WmiObject. Or you can specify $ErrorActionPreference = "stop" if you want that all Cdmlet throw Exception on errors.

Community
  • 1
  • 1
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • 1
    That last line `$ErrorActionPreference = "stop"` is very important and convenient for `try {} catch {}` to work as expected. That if anything inside the `try {}` causes any error it will cause the `catch{}` to be run. – BeowulfNode42 Feb 14 '14 at 08:36
1

Try/catch works only with terminating errors. In my experience, 99% of errors produced by Get-WmiObject are not terminating so catch wont have any effect in this case.

One thing you can do is make the any error thrown by the command a terminating error, you can do that with the -ErrorAction Stop. Passing 'stop' will make the error a terminating error allowing the catch block to invoke

Shay Levy
  • 121,444
  • 32
  • 184
  • 206