Run Script or Command as Admin in Powershell

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:

Access denied error, seen here in its natural habitat.

 

 

 

 

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:

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:

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!

Bookmark the permalink.

Leave a Reply

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