Windows shortcut for PowerShell script with relative path

When creating a Windows shortcut to run the PowerShell script, the following works fine if you double-click it as a regular user and right-click Run as administrator :

 %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy "Bypass" -Command "&{& 'C:\Script.ps1'}" 

Screenshot example

However, when the path is relative and unknown in advance, the following works fine if you double-click it as a normal user, but without right-clicking Run as administrator :

 %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy "Bypass" -Command "&{& '.\Script.ps1'}" 

My question is, how can I make it work in both cases when the path is relative? I tried using PSScriptRoot , but that didn't work either.

Thank you for your help.

+2
source share
1 answer

When running as an administrator from Explorer, you must specify the absolute path to the script.

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

An easy way to start in another directory is to change the directory at the beginning of your script. The next line will be cd in the directory where the script is located.

 Set-Location $PsScriptRoot 

If the script needs to be run in a different path, you may need to write a function to find where this path is located on the local machine (for example, listing USB drives )

+2
source

All Articles