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:
Mounir, when you right-click on the Command Prompt (cmd) from the start menu and you choose 'Run as Administrator', then you basically, execute that file with a code like my code-snippet (above), except that, that code is written in C. Have a nice day. My plan is to run this batch file one night with a temp domain account that I previously add to local admin group of all PCs an hour before running this and then I disable that account in the morning. My issue is I keep getting prompted for a password which not gonna do what I need runas /user:MYDOMAIN USER.
Bat File Open Cmd As Administrator Manager
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:
Start-Processpowershell.exe-VerbRunas-ArgumentList'-Command & {get-process}'
Cannot Open Cmd As Administrator
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!