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

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:

UAC elevation code:

Check for Admin rights code:

Edited: 9-4-15 Thanks Hh Lohmann