Thursday, October 13, 2011

Check to see if a VBS script has Admin rights


Came across a problem today where we were running a VBS script that was obviously designed expecting UAC to be turned off.  In looking for a way to elevate the script to Admin before running, I found some code to force the script to run as administrator without having to reghack each PC.  It took a combination of sites to get the code, but here it is.

On Error Resume Next
key = CreateObject("WScript.Shell").RegRead("HKEY_USERS\s-1-5-19\")
If err.number <> 0 Then
 Set objShell = CreateObject("Shell.Application")
 objShell.ShellExecute "wscript.exe", Chr(34) & _
 WScript.ScriptFullName & Chr(34), "", "runas", 1
 WScript.Quit()

End If


If you insert that code at the beginning of your script it will first check to see if the script has Administrative rights (Either through UAC, or XP admin) and if it doesn't it will relaunch the script using runas administrator.

Warning: I haven't tested this in Windows XP.  I know that the Check part will work, but don't know about the relaunch.


Reghack to get Run As Administrator in the context menu for .VBS files:
http://www.sevenforums.com/tutorials/152967-run-administrator-add-vbs-file-context-menu.html

UAC elevation code:
http://www.winhelponline.com/articles/185/1/VBScripts-and-UAC-elevation.html

Check for Admin rights code:
http://csi-windows.com/toolkit/csi-isadmin

Edited: 9-4-15 Thanks Hh Lohmann

2 comments:

hh.lohmann said...

Elegant & effective, but you need two additional statements to make it work as intended:

1. "On Error Resume Next" somewhere before "key = ...", otherwise the script will just end with an error if you are trying to RegRead "HKEY_USERS\s-1-5-19\" as a non-admin or as an unelevated admin (UAC)

2. "WScript.Quit()" at the end (inside) of the If clause / after ShellExecute, otherwise your script will run twice, one instance with admin rights / elevation (the "restarted" with ShellExecute), another without (ordinary that what follows in your code after the If clause), and the latter might spoil overall execution

Though 4 years have passed since your post, admin / UAC problems come back with Windows 10 where simply turning off UAC is neither the best nor the easiest way.

Unknown said...

And add On Error Resume after the End If to reinstall Error checking.