2
function Test($cmd)
{
          Try
         {
                  Invoke-Expression $cmd -ErrorAction Stop
         }
         Catch
         {
                  Write-Host "Inside catch"
         }

         Write-Host "Outside catch"
}

$cmd = "vgc-monitors.exe"  #Invalid EXE
Test $cmd

$cmd = "Get-Content `"C:\Users\Administrator\Desktop\PS\lib\11.txt`""
Test $cmd
#

Call Test() first time with $cmd = "vgc-monitors.exe" (this exe does not exist in system)

*Exception caught successfully

*Text "Inside catch" "outside catch" printed

#

Call Test() second time with $cmd = "Get-Content "C:\Users\Administrator\Desktop\PS\lib\11.txt"" (11.txt does not exist in the specified path)

*Exception NOT caught

*Text "Inside catch" not printed"

*Get the following error message

Get-Content : Cannot find path 'C:\Users\Administrator\Desktop\PS\lib\11.txt' because it does not exist.
At line:1 char:12
+ Get-Content <<<<  "C:\Users\Administrator\Desktop\PS\lib\11.txt"
    + CategoryInfo          : ObjectNotFound: (C:\Users\Admini...p\PS\lib\11.txt:String) [Get-Content], ItemNotFoundEx
   ception
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Question:

I want the second exception to be caught. I cannot figure out the error in my code.

Thanks

Jugari

1 Answer 1

2

You're applying -ErrorAction Stop to Invoke-Expression, which executes just fine. To make the error action directive apply to the invoked expression you'd need to append it to $cmd:

Invoke-Expression "$cmd -ErrorAction Stop"

or set $ErrorActionPreference = "Stop":

$eap = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
  Invoke-Expression $cmd
} catch {
  Write-Host "Inside catch"
}
$ErrorActionPreference = $eap

The latter is the more robust approach, as it doesn't make assumptions about $cmd.

Sign up to request clarification or add additional context in comments.

3 Comments

What if $cmd happens to be an exe? Or for some reason they decided to end the command with a ;?
@KeithHill Then he'd just have to stick with second option I suggested.
That would be preferable I think. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.