user2088807
user2088807

Reputation: 1408

get the exit code of a wpf application in powershell

I'm trying to get the exit code of my wpf application called in a Powershell script.

My main in WPF :

[STAThread]
public static int Main(string[] args)
{
    if (args != null && args.Length > 0)
    {
        NB_ERRORS = AutomaticTests.Program.Main(args);
        return NB_ERRORS;
        //Application.Current.Shutdown(NB_ERRORS);
    }
    else
    {
        App app = new App();
        app.Run(new MainWindow());

        //Application.Current.Shutdown(NB_ERRORS);
        return NB_ERRORS;
    }
}

And in powershell I call it like this :

& $PathToExeTests 0 $LogTestsStagging
$nbFailed = $LASTEXITCODE

But it always contains 0.

I've tried to manually set the Environment.ExitCode, to shutdown the application with the code, to override OnExit like this :

protected override void OnExit(ExitEventArgs e)
{
    e.ApplicationExitCode = AutomaticTests.GUI.Program.NB_ERRORS;
    base.OnExit(e);
}

But I always have 0 in the LastExitCode.

Upvotes: 4

Views: 1131

Answers (1)

Joe White
Joe White

Reputation: 97778

By default, when you start a GUI app, PowerShell (just like cmd.exe) will not wait for the app to exit; it'll just tell Windows to start loading the app, and then continue running the script.

There are a couple of ways to wait for a GUI app to exit.

Option 1: Start the app using Start-Process, and then pass the resulting Process object to Wait-Process. This can be easily written as a pipeline:

Start-Process $PathToExeTests -ArgumentList @(0, $LogTestsStaging) | Wait-Process

Option 2: If you do something with the app's standard output (assign it into a variable, or pipe it into another command), then PowerShell will automatically wait for the process to exit.

& $PathToExeTests 0 $LogTestsStaging | Out-Null

Option 1 is probably going to be a lot more readable if someone else is ever going to maintain your code, but occasionally you'll see option 2 as well.

Upvotes: 1

Related Questions