Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Powershell: Issue with Try-Catch block

$
0
0

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



Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>