How Can I Use the RunAs Command to Run a Script Under Alternate User Credentials?

23Jul

How Can I Use the RunAs Command to Run a Script Under Alternate User Credentials?

So is this really a problem? Well, it can be. After all, Microsoft recommends that – for security reasons – you never log on to a computer using an Administrator account. Instead, we suggest that you log on using a regular old user account, then use a utility such as RunAs any time you need to run a program as an Administrator. And so, seeing as how everyone always does whatever Microsoft tells you to do, you type the following command at the command prompt and try using the RunAs utility to run the script C:\Scripts\Test.vbs:

runas /profile /user:domain\useradmin "C:\Scripts\Test.vbs"

And here’s what happens when you press ENTER:

Attempting to start C:\Scripts\Test.vbs as user "domain\useradmin" ...
RUNAS ERROR: Unable to run - C:\Scripts\Test.vbs
193: C:\Scripts\Test.vbs is not a valid Win32 application.

It’s at this point that people typically do one of two things: either they give up, or they start debugging the script, trying to figure out why their code isn’t valid. But here’s the deal: the error message says nothing about the script or the script code being invalid, it simply states that Test.vbs is not a valid Win32 application. That’s because RunAs is expecting to run an executable file. Test.vbs is obviously not an executable file, so the command fails. Most likely your code is just fine; the problem is that you’re trying to run a script rather than a .exe file.

So if RunAs accepts only executable files then obviously we can’t run a script using RunAs, right? Well, not necessarily. Although Test.vbs might not be an executable file, the two Windows script hosts – Cscript.exe and Wscript.exe – are executable files. The secret to running a script under RunAs is to call one of the two script hosts, passing along the name of the script as a command-line argument. For example, this RunAs command will fire up Cscript.exe and then run the script C:\Scripts\Test.vbs: