views:

49

answers:

2

Hi,

I have this simple script:

$files = dir .\configs | ? { !$_.PSIsContainer }

foreach($file in $files)
{
    try
    {
        .\MyApp.exe -ErrorAction Stop $file
    }
    catch
    {
         write-host "!!!!!!!!!!!!error!!!!!!!!!!!!!!"
         continue
    }   
}

The problem is that when

.\MyApp.exe -ErrorAction Stop $file

crash, the windows message box about application crash appear and my script block, catch is not hit and only way to continue is click Storno button in the message box.

So how to prevent blocking?

+1  A: 

Several notes apply here:

  • This dialog is managed by operating system, so there is nothing about PowerShell. PowerShell can't do anything about it. You could use some automation to find a window and 'click' button, but that's really awkward.
  • Also applying parameters like -ErrorAction has no value. That applies only to functions/cmdlets (anything else?).
  • Applications are supposed to return 0 (success) or anything else (failure), they don't throw exceptions. In your case you can use $lastexitcode that contains the exit code of the application.

Note, that properly coded application should really return its exit code and may write something to console. If it fails horribly with that message box, there is no excuse. At least one big try/catch block in the Main function should be used.

stej
I tried use $lastexitcode, but it is set after click on storno in message box.
tomasK
Edited the answer. I really think you can only find awkward workaround.
stej
But some time ago, it work for me in PowerShell 1.0 using trap, without blocking. But now I am not able to reproduce it...
tomasK
tomasK, probably because the app was not crashing before. :)
JasonMArcher
A: 

.\MyApp.exe -ErrorAction Stop $file

On a side note, -ErrorAction has no meaning in legacy applications. It's a cmdlet parameter.

Shay Levy