David Rigdon

Systems Administrator

Self-Elevate Powershell Snippet | David Rigdon

Self-Elevate Powershell Snippet

October 23, 2023

Snippet Breakdown

This is by far one of my most favorite snippets… To use, paste this snippet at the beginning of your script, and when it runs it determines if it is running in an elevated session, and if not re-launches script to be elevated:

if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
    if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
     $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
     Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
     Exit
    }
   }