Executing Elevated PowerShell Code

by Dec 17, 2012

Sometimes, a script may want to execute some portion of its code elevated, for example to write to HKLM in the Registry or change protected settings. Instead of requiring the user to run the entire script elevated, you can execute portions of it in a separate PowerShell that gets elevated automatically.

This line, for example, will create a Registry key in the protected HKLM hive. If the script runs elevated already, the key will just be created. If the script has no special privileges, a UAC elevation prompt appears and elevates the script portion that needs it:

PS> $code = 'New-Item hklm:\software\somekey2'
PS> Start-Process -FilePath PowerShell -Verb Runas -WindowStyle Minimized -ArgumentList (' -noprofile -noexit -command ' + $code)
PS> Test-Path hklm:\software\somekey
True

Twitter This Tip! ReTweet this Tip!