A coworker of mine was writing a script to simplify some configuration items on some servers, and he ran into a snag. If you’ve worked in IT for at least a day, you’ve seen this message at some point:
This is easily solved using the old right-click -> Run as Administrator routine, but what if you need a script to run a command, or an entire script as administrator? In this post I go through the three scenarios I’ve come across for running some Powershell commands as an administrator; a single command, an entire .ps1 or batch file, and a entire script from within the script calling it.
Run a single command as administrator
to run a single command as an administrator, we can the Start-Process cmdlet and pass in our command via the -Command parameter of powershell.exe. The -Command parameter is passed to the EXE from Powershell via the -ArgumentsList parameter of the Start-Process cmdlet. Finally, our command we want to run in our admin session is inside of curly braces preceded by the invoke operator (&). If that sounds confusing, hopefully this will help:
1 |
Start-Process powershell.exe -Verb Runas -ArgumentList "-Command & {get-process}" |
Run a .ps1 file as an administrator
Running an entire script as an administrator is similar, we just replace the -Command parameter with -File, remove the invoke operator, and define the file path to our script, like so:
1 |
Start-Process powershell.exe -Verb Runas -ArgumentList "-File D:\Scripts\Get-Process.ps1" |
It’s worth noting that these assume that the user running the script is an administrator. If they aren’t, you will still have access denied issues. Hope this helps, and happy scripting!