Windows shortcut to a PowerShell script with relative path Windows shortcut to a PowerShell script with relative path powershell powershell

Windows shortcut to a PowerShell script with relative path


When launching as admin from Explorer, you must provide an absolute path to the script.

Explorer.exe ignores the starting directory from the shortcut when launching a process as admin. Instead, Admin-level processes always launch with the current directory in [Environment]::GetFolderPath('System') (usually C:\Windows\System32)

The easy way to run in a different directory is to change directory at the beginning of your script. The following line will cd to the directory the script is in.

Set-Location $PsScriptRoot

If the script needs to start in a different path, then you may have to write a function to discover where that path is on the local machine (such as enumerating USB drives)


You can use your current solution for non-admin promoted shortcuts then auto promote the script internally:

# ========================================= Admin Rights =======================================================# Usage: asAdmin $PSCommandPathfunction asAdmin{    [string]$cmdPath = $args[0]    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$cmdPath`"" -Verb RunAs; exit }}