I have a powershell script that checks if it's admin, and if not relaunches as admin. However, I've had to add a parameter to tell the script what interpreter to use on relaunch (pwsh.exe or powershell.exe in particular). Is there a way to tell which .exe is executing the script?
param (
[string]$AdminShell = "powershell.exe"
)
# Check if the script is running as administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
# Restart the script as administrator
Start-Process -FilePath $AdminShell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File $($MyInvocation.MyCommand.Path)" -Verb RunAs
Exit
}
You can use GetCommandLineArgs
to determine it. The first argument (index 0
) will be the shell's absolute path.
[System.IO.Path]::ChangeExtension([System.Environment]::GetCommandLineArgs()[0], 'exe')
Another option is with Get-Process
using $PID
automatic variable:
(Get-Process -Id $PID).Path
A third option is pointed out by Mathias in comments, using either $PSVersionTable
or $IsCoreCLR
, both options should be valid:
if ($IsCoreCLR) {
Join-Path $PSHOME pwsh.exe
}
else {
Join-Path $PSHOME powershell.exe
}