powershellstart-process

How can I call powershell.exe via Start-Process, to then call a script with its own parameters and capture the exit code?


I can't figure out the syntax for this, I have a config script that needs to be called from another script. When I call the config script manually, it looks like this config.ps1 -val1 "1234" -val2 "12.089" . I need to use Start-Process to call config.ps1 with the parameters as well as to not open a new window (non interactive) and to capture the exit code of config.ps1 and wait for it to return an exit code before proceeding further.

Here is what I've tried most recently

$process = Start-Process powershell.exe -FilePath "c:\config.ps1" -ArgumentList -val1 "1234" -val2 "12.089" -PassThru -WindowStyle Hidden -Wait;

Solution

  • Building on Daniel's helpful comments.

    The problem with your code:

    $process = Start-Process powershell.exe -FilePath "c:\config.ps1" -ArgumentList -val1 "1234" -val2 "12.089" -PassThru -WindowStyle Hidden -Wait

    Thus, the immediate fix is (-WindowStyle Hidden omitted for brevity; note the addition of -File and the use of a verbatim here-string (@'<newline>...<newline>'@) to simplify embedded quoting):

    $process = 
      Start-Process -PassThru -Wait -FilePath powershell.exe -ArgumentList @'
       -File "c:\config.ps1" -val1 "1234" -val2 "12.089"
    '@
    

    Note that while in this particular case omitting the -File parameter of powershell.exe, the Windows PowerShell CLI, would have worked in principle too - in which case -Command is implied, there is an important difference:

    $process.ExitCode then reflects the script's exit code.


    Taking a step back:

    Note:


    [1] See this answer for more information.

    [2] See this answer for more information.

    [3] See this answer for more information.

    [4] See GitHub issue #7989 for a discussion of this problematic behavior.