Powershell – run as admin (elevated permissions)

Powershell – run as admin (elevated permissions)

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
   break
}

It will check if it’s already running with administrative privileges, and if not, will restart itself running as admin.

Simple and convenient ๐Ÿ™‚

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *