Skip to content

Instantly share code, notes, and snippets.

@cjfarrelly
Last active July 26, 2022 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjfarrelly/1c1609913b1de1d602c2 to your computer and use it in GitHub Desktop.
Save cjfarrelly/1c1609913b1de1d602c2 to your computer and use it in GitHub Desktop.
Powershell self elevating as admin in 64bit mode script
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
Clear-Host
}
else
{
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$scriptName = $myInvocation.MyCommand.Definition
$newProcess.Arguments = "-File $scriptName"
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit
}
if ($pshome -like "*syswow64*") {
write-warning "Restarting script under 64 bit powershell"
& (join-path ($pshome -replace "syswow64", "sysnative") powershell.exe) -file `
(join-path $psscriptroot $myinvocation.mycommand) @args
exit
}
Set-ExecutionPolicy RemoteSigned -Force
#add your code here
@cjfarrelly
Copy link
Author

Combined code I found on the two sites below, this came in handy when running scripts as part of TFS builds on various agents.

http://poshcode.org/3827
http://blogs.msdn.com/b/virtual_pc_guy/archive/2010/09/23/a-self-elevating-powershell-script.aspx

@vivek1986
Copy link

Why not just use a small, no-need-changes one-liner that not only self-elevates the script, but also remembers your working/current directory:

$Loc = Get-Location
"Security.Principal.Windows" | % { IEX "( [ $_`Principal ] [$_`Identity ]::GetCurrent() ).IsInRole( 'Administrator' )" } | ? {
    $True | % { $Arguments =  @('-NoProfile','-ExecutionPolicy Bypass','-NoExit','-File',"`"$($MyInvocation.MyCommand.Path)`"","\`"$Loc\`"");
    Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Arguments; } }

(Get-Location).ToString()
## Any PS code that needs elevation
Read-Host

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment