Is there a way to catch exceptions that were thrown by exe files in powershell scripts?

I am writing a powershell script that mimics the behavior of a watch. It works fine until I look at an exe that throws an exception.

When this happens, the Visual Studio JIT debugger starts up and opens a dialog box. I tried to catch the exception using the try / catch block, as in the code example below.

I know that I can enable the debugger in VS, but I do not want to use it, since it is useful for debugging. I just want to catch / disable the exception and the popup when it occurs in this script.

I have read several sources that claim this is not feasible in powershell, but I hope that they are wrong and that there are some smart ways to solve the problem. Does anyone have any clues?

What I tried:

$tick = "-"

while ($true)
{
    try {
        $out = invoke-expression "$args"
    }
    catch {
        $out = "Error: " + $_.Exception.Message
    } finally {
        cls
        $out
        $tick
        if ($tick -eq "-") {$tick = "+"} else {$tick = "-"}
        sleep 1 
    }
}    

I also tried adding [Exception]and [System.IO.IOException](the specific exception I received) to the catch block, but no luck anymore.

+4
source share
2 answers

Exe uses exit codes to return error status instead of .NET exceptions. A workaround is to check $ lasterrorexitcode. If you want to use try / catch blocks, you can issue a throw command if lasterrorcode is not zero. Note. One thing to watch out for: some exes use non-zero error codes to return a status other than an error.

Here is an example:

Wrap a try / catch block

try {
    $result = some-exe.exe

    if ($lastexitcode -ne 0) {

        $result = $result -join "`n"
        throw "$result `n"
    }
}
catch {
  write-error "$_"
}
0
source

() ( " ", )

  • PowerShell WASP ( Codeplex), EXE, , , .

  • system.diagnostics.process EXE : Disposed, ErrorDataReceived Exited, EXE .

  • EXE , Main, try/catch.

0

All Articles