Some of the scripts on this page are full scripts to accomplish a task, others are snippets you can copy/paste into scripts you're building.
Self-elevate a Powershell script
The following code will re-launch a Powershell session as an Administrator, using the same Powershell version as the non-elevated session that called it.
## Determine which shell is running (PowerShell 7+ or Windows PowerShell)$shellPath=if($PSVersionTable.PSEdition-eq'Core'){## PowerShell 7+, use current process path (e.g., pwsh.exe)(Get-Process-Id$PID).Path}else{## Windows PowerShell 5.1"$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe"}## Relaunch with elevation if not already running as adminif(-not([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){Write-Warning"Relaunching as Administrator"Start-Process-FilePath$shellPath`-ArgumentList"-NoProfile","-ExecutionPolicy Bypass","-File `"$PSCommandPath`""`-VerbRunAsexit}## Rest of your code here