Windows – Run PowerShell Script as Administrator in the Same Directory as Original Script

administratorpowershellscriptwindows 10

So apparently there's no easy way to directly run a .ps1 script as administrator by double clicking it; you can edit the registry to run it, but then in order to make it run as administrator, apparently you have to tell it to open a new elevated PowerShell from within the already running PowerShell. Unfortunately, as far as I've been able to see, every time this is done, the elevated prompt opens up in a different directory than the original script! So, for example, if I have the following script:

$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
  .\mylocalscript.ps1
  Write-Host "Just an example!"
}
else
{
  Start-Process -FilePath "powershell" -ArgumentList "-NoExit $('-File ""')$(Get-Location)$('\')$($MyInvocation.MyCommand.Path)$('""')" -Verb runAs
}

It fails because, upon being opened as administrator, the local script that was once local to the original script is no longer local, and then it cannot find it. Essentially, I need a way to tell the new elevated PowerShell window that opens to automatically change back to the directory of the original script.

What's the best way to do this?

Best Answer

You can use set-location with -Path $PSScriptRoot to change to the directory which the script that contains those commands reside, and then you can run the rest of your logic after that command to ensure it is set back to the needed directory before any commands run.

Set-Location -Path $PSScriptRoot

Further Resources

  • Set-Location
  • Automatic Variables

    • $PSScriptRoot

      Contains the directory from which the script module is being executed. This variable allows scripts to use the module path to access other resources. In PowerShell 3.0+ this is available everywhere, not just in modules.

Related Question