1
votes

I'm currently working on a PowerShell script that includes the line

$process1 = Start-Process -FilePath ($exePath1) -PassThru -RedirectStandardError ($logPath1)

Which starts a long-running process and redirects the process' StandardError to a log file. My problem is that this also apparently interferes with ExitCode.

$process1.ExitCode

returns null after the process has exited. If I remove "RedirectStandardError ($logPath1)" then ExitCode returns the value my dummy-program is expected to return.

Should I be doing something different? I'm hoping to be able to start the process (redirecting the StandardError to the log file for diagnostics), wait a few seconds to make sure it doesn't crash, and retrieve the ErrorCode in the event that it does.

1
use $process1.WaitForExit() firstly before obtaining the $process1.ExitCode. - t0mm13b
@t0mm13b: I'm using $process1.HasExited. The process in question is very vulnerable to configuration mistakes, so I want to start it up and make sure that it didn't crash out. - dornadigital

1 Answers

1
votes

If you need to wait for the process and you're not running it as a different user:

$StartParams = @{
    FilePath = $exePath1
    RedirectStandardError = $logPath1
    PassThru = $True
    Wait = $True
}
$ReturnCode = (Start-Process @StartParams).ExitCode

Since it's long-running, here's an alternative method with PSJobs:

$Job = Start-Job -ScriptBlock {
    $StartParams = @{
        FilePath = $exePath1
        RedirectStandardError = $logPath1
        PassThru = $True
        Wait = $True
    }
    (Start-Process @StartParams).ExitCode
}
If ($Job.State -eq 'Completed')
{
    $ReturnCode = Receive-Job -Job $Job
}