YorSubs
YorSubs

Reputation: 4050

PowerShell find path to currently running host (PowerShell executable)

I can find the path to a running script, but I can't find the path to the running host. I want this because we could be running PowerShell or PowerShell Core 6 or PowerShell Core 7 from a given script, which could be running on Windows or Linux. Googling around this is not obvious (I just get pages telling me how to find the path to the running script). Does anyone know how to find the path to the running host?

Upvotes: 6

Views: 1878

Answers (3)

mklement0
mklement0

Reputation: 437353

To determine the full path of the executable that launched the process in which PowerShell runs:

# Works with both PowerShell editions, on all platforms.
(Get-Process -Id $PID).Path

Automatic variable $PID contains the current process' PID (process ID).

Note:

  • On Unix platforms, if PowerShell was started via a symlink, the above reports the actual location of the executable, not that of the symlink.

  • In PowerShell (Core) 7, you may alternatively use the following:

    # PowerShell 7.2+ only.
    [Environment]::ProcessPath
    

Upvotes: 9

Maybe
Maybe

Reputation: 965

The fastest way (in terms of performance) to accomplish this is with the GetCurrentProcess method:

[Diagnostics.Process]::GetCurrentProcess().Path

The path of the current Powershell binary will be the output, even if PowerShell was started via a shim or a symbolic link (regardless of platform).

Upvotes: 2

wasif
wasif

Reputation: 15480

You can use:

(Get-Process Powershell).Path

Or

Join-Path -Path "$($PSHOME)" -ChildPath "powershell.exe"

to get the path of running host.

Upvotes: 2

Related Questions