Last active
July 26, 2022 01:48
-
-
Save cjfarrelly/1c1609913b1de1d602c2 to your computer and use it in GitHub Desktop.
Powershell self elevating as admin in 64bit mode script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
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
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