3

When creating a Windows shortcut to launch a PowerShell script the following works fine when double clicked as a regular user and with right click Run as administrator:

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

Example screenshot

However, when the path is relative and not known upfront the following works fine when double clicked as a regular user but not with right click Run as administrator:

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

My question, how can I have 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.

DarkLite1
  • 12,007
  • 34
  • 105
  • 185
  • Relative to what? Your `Start in` box is blank in the screenshot. Are you filling that box, or is there some other path you're using to start from? – Ryan Bemrose Jul 29 '16 at 18:30
  • Here's my solution to this problem: http://stackoverflow.com/a/35054677/368889 – Mica Sep 08 '16 at 05:42

2 Answers2

2

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)

Ryan Bemrose
  • 8,538
  • 37
  • 51
  • Thanks for the help Ryan. The problem is that the script launcher and script can be on a USB stick or on a network share somewhere. So the location where it's located is different. Can this be accounted for with `Set-Location`? And indeed, the `Start in` stays empty as we don't know that upfront. – DarkLite1 Aug 01 '16 at 08:15
  • Updated the answer to be a bit simpler. BTW, `Set-Location` is the same as `cd` . The latter is just an alias for the former. – Ryan Bemrose Aug 01 '16 at 15:09
0

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

# ========================================= Admin Rights =======================================================
# Usage: asAdmin $PSCommandPath
function 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 }
}
Geordie
  • 1,496
  • 1
  • 18
  • 28