Every now and then I find myself in need of running a powershell script with administrative privileges (i.e. to set a registry key).
And since every time I end up doing a quick search, I thought I’ll keep this small snippet handy 🙂
Simply put this at the beginning of the .ps1 file, and continue with your script below:
# Re-run this script with admin privileges if not already running
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
It will check if it’s already running with administrative privileges, and if not, will restart itself running as admin.
Simple and convenient 🙂