VBScripts and UAC elevation

With User Account Control (UAC) enabled in Windows Vista, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script under elevated privileges, without using the Command Prompt? comes to our mind.

Applications can make use of manifest files (using RequireAdministrator flag) to show the elevation dialog when run. As far as I know, there is no such option for scripts. Using the ShellExecute method, you can elevate a script by passing the runas parameter. Thanks to Jim Barry for tipping me off about the ShellExecute method of Shell.Application object. Using Jim's suggestions, my original script was condensed down to a great deal. Use one of these methods to run VBScripts elevated.

Method 1

This re-launches the current VBScript as administrator (elevated) if the script has no command-line arguments passed. When re-launching the script as administrator, simply pass a bogus argument so that the script does not run in a cyclic loop.

If WScript.Arguments.length =0 Then
  Set objShell = CreateObject("Shell.Application")
  'Pass a bogus argument with leading blank space, say [ uac]
  objShell.ShellExecute "wscript.exe", Chr(34) & _
  WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
  'Add your code here
End If

Method 2

This method uses a stub or wrapper script which runs the main VBScript elevated using the runas verb.

Set objShell = CreateObject("Shell.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
strPath = FSO.GetParentFolderName (WScript.ScriptFullName)
If FSO.FileExists(strPath & "\MAIN.VBS") Then
     objShell.ShellExecute "wscript.exe", _
        Chr(34) & strPath & "\MAIN.VBS" & Chr(34), "", "runas", 1
Else
     MsgBox "Script file MAIN.VBS not found"
End If

You'll see see the UAC elevation dialog as in the figure below:

Once user clicks Continue to approve, the main script is launched, which runs under administrator privileges.

NOTE: The sample wrapper script above, looks for the main script (Main.vbs) in the same folder where the wrapper script resides. Feel free to alter the code to customize it according to your requirements, or to add error handling routines if you want. Also, it would help the end-user if you give the wrapper script an intuitive name, such as launch.vbs or run.vbs.