Search code examples
windowspowershellpowershell-3.0powershell-4.0

Converting if-else to try-catch within PS


I have the following PS command which is as follows:

    if(get-customcmdlet) {
           $var = var1
        } else {
            $var = var2
}

Here get-customcmdlet is throwing an exception.

So, I have modified the above statement as follows:

try {
  get-customcmdlet
  $var = var1
}
catch {
$var = var2
}

Please let me know if it is correct way to handle the exception generated from get-customcmdlet


Solution

  • You have to understand that try-catch does something different than your earlier if-else.

    Try-Catch checks if a execption is thrown, while if(get-customcmdlet) checks if your function returns something unequal $false or $null.

    Given that your function supplies something even when an exception occurs on one point, you can just combine both toghether like this:

    try {
      if(get-customcmdlet) {
          $var = var1
      }
      else {
          $var = var2
      }
    }
    catch {
      $var = var2
    }
    

    This way $var equals var2 when the function returns an exception and when it returns nothing or $false.