Launch program in current PowerShell terminal

Viewed 332

I'm trying to run a command that uses a variable as the executable. In Cmd, I would just do the following:

%MY_PROGRAM% -my_program_option

I'm trying to do the same in PowerShell doing this, but it always launches in a new command (not PowerShell) terminal:

Invoke-Expression "${MY_PROGRAM} -my_program_option"

How can I make it launch in the current PowerShell terminal session?

1 Answers
& ${MY_PROGRAM} -my_program_option

If ${MY_PROGRAM} refers to a console application, it should:

  • execute in the same window
  • synchronously (i.e. PowerShell will wait until the application exits before continuing)
  • with the application's output streams connected to PowerShell's streams, which enables directly collecting or redirecting the application's output.

As for what makes an application a console application: a flag in a given executable indicates whether it is a console-subsystem or a GUI-subsystem executable (note that these are Windows-only concepts).

Behavioral implications:

  • If a given executable is a console-subsystem executable, PowerShell executes it in the same window, in the manner described above.

    • Note: This also applies to directly invoked script files that are associated with console-subsystem executables, assuming their filename extensions are listed in the $env:PATHEXT environment variable so as to allow their direct execution; e.g., .cmd or .bat.
  • By contrast, a GUI-subsystem executable launches asynchronously - with no further connection to the calling session - and it is free to create its own GUI, including potentially creating a new console window, or even no UI at all.

    • You can use Start-Process if you need more control over calling such applications.
Related