Petrroll
Petrroll

Reputation: 761

Run command script as separate process powershell.exe and pwsh.exe compatible

Is there any easy way to invoke a powershell script in separate process while being cross-platform (i.e. supporting both powershell.exe and pwsh.exe, and ideally powershell on linux (not required)).

If only supporting powershell.exe would be requirement I know I can do

$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -NoNewWindow -ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
$process.WaitForExit($waitTimeMilliseconds)

I could see that I could try to find out if I'm running powershell.exe or pwsh.exe and do some heuristic for the powershell path but it all seems weirdly convoluted... isn't here some better way?


A slightly better approach might be to use $PSHome variable, e.g.: via

 & $PSHOME\powershell.exe -Command '$PID'

But even that has the issue of pwsh pshome not containing powershell.exe but rather only pwsh.exe.

Upvotes: 4

Views: 1399

Answers (1)

stackprotector
stackprotector

Reputation: 13432

You can use (Get-Process -Id $PID).Path to determine the executable of your current PowerShell and use that to start another process of it:

Start-Process (Get-Process -Id $PID).Path

It is "cross-platform" and works with PowerShell and PowerShell Core. It even works with PowerShell Core on Linux, as long as you don't call it interactively (calling PowerShell with Start-Process seems to break the CLI on Ubuntu 20.04 LTS, but it works when using it to execute a script file). Docs:

$PID

Contains the process identifier (PID) of the process that is hosting the current PowerShell session.

Upvotes: 4

Related Questions