Automatically elevate PowerShell script while retaining current directory



When you right-click on a PS1 file and select "Run with PowerShell" it will run as the local user, now if you are not logged in as an administrator that will cause you to run into some issues as the script may not have access to run certain commands in your script.

For simplification when running scripts the following code can be added to the top of your script, this code checks if the current user is an Administrator, then if they are proceed, otherwise start a new PowerShell instance as administrator and prompt for authentication.

The added bonus to this script is that it keeps the current directory in the new instance so if your script is location dependent and needs to save files in a relative location this script works well.

The following code is a modified version of code published to superuser.com and is available on my github.


Param(
    [string]$Loc
)

$Delay = 2

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole] 'Administrator')
)
{
    Write-Host "Not elevated, restarting in $Delay seconds ..."
    $Loc = Get-Location
    Start-Sleep -Seconds $Delay

    $Arguments =  @(
        '-NoProfile',
        '-ExecutionPolicy Bypass',
        '-NoExit',
        '-File',
        "`"$($MyInvocation.MyCommand.Path)`"",
        "\`"$Loc\`""
    )
    Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Arguments
    Break
}
else
{
    Write-Host "Already elevated, exiting in $Delay seconds..."
    Start-Sleep -Seconds $Delay
}
if($Loc.Length -gt 1){
Set-Location $($Loc.Substring(1,$Loc.Length-1)).Trim()
}

#Your Script Here...
Read-Host "Done.."




Was this helpful?

Yes No


Comments