Running Portions of Code Elevated

by Jun 17, 2013

Let's assume your script may or may not need to do a privileged operation, for example write a value to a HKEY_LOCAL_MACHINE branch, depending on some prerequisites. Instead of having to run the entire script with Administrator privileges, you can run only those parts requiring it:

function Start-ElevatedCode
{
  param([ScriptBlock]$Code)

  Start-Process -FilePath powershell.exe -Verb RunAs -ArgumentList $Code

}

This will launch a new elevated PowerShell console, and runs the code you submit. Of course, the user has to click the UAC dialog or submit user credentials to run it.

Twitter This Tip! ReTweet this Tip!