Executing Selected Code as Admin

by Aug 25, 2015

If you need to run selected parts of your script with Administrator privileges, you could temporarily launch a second PowerShell with Administrator privileges, then run the privileged command in the temporary shell.

Here is a sample that stops the Windows Update service. When you run it as regular user, it automatically pops up the elevation dialog, then executes your code in the new admin shell:

#requires -Version 2

Start-Process -FilePath powershell.exe -Verb runas -ArgumentList 'Stop-Service -Name wuauserv' -WindowStyle Minimized

Twitter This Tip! ReTweet this Tip!