Reputation: 433
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
Upvotes: 2
Views: 2931
Reputation: 200203
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
.
Upvotes: 2