Last active
March 19, 2025 09:18
-
-
Save mcc85s/785e7c83d14bd57cb7a52a2eefc94f73 to your computer and use it in GitHub Desktop.
self elevating powershell script
This file contains hidden or 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
$ID = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() | |
If (!($ID.IsInRole("Administrator") -or $ID.IsInRole("Administrators"))) | |
{ | |
If (Get-CimInstance Win32_OperatingSystem | ? { [UInt32]$_.BuildNumber -ge 6000 }) | |
{ | |
Write-Host "Not running as admin, attempting elevation..." | |
$Command = $MyInvocation | % { "-File `"{0} {1}`"; Exit" -f $_.MyCommand.Path, $_.UnboundArguments } | |
Start-Process PowerShell -Verb Runas -Args $Command | |
} | |
Else | |
{ | |
Throw "Must run as an administrator." | |
} | |
} |
GCIM 6000 有什么特别或必要的,我试过了,这也运行得很好(Windows 10/11),而且它不会忘记当前目录:
$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
With the help of ChatGPT, after numerous attempts, I have managed to write the shortest code for self-elevating PowerShell permissions:
if (-not (net session 2>$null)) { Start-Process powershell -WorkingDirectory "$PSScriptRoot" -ArgumentList "-File `"$PSCommandPath`"" -Verb RunAs; exit }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's so special or necessary about GCIM 6000, I tried and this works pretty good too(Windows 10/11) and it doesn't forget current directory: