How to Launch a WSH VBScript as Administrator in Windows 7 and Vista


  • Share on Pinterest

The example below launches a VB script as administrator on Windows 7 and Vista regardless if the context menu contains the “Run as administrator” option. Registry tweaks exist to add the run as administrator option to the context menu for .vbs files but this creates complications if the script is distributed to other people.

When the script below is executed it checks to see if it was passed a command line argument named “elevated”. If it is not found the script recursively calls itself passing the elevated command line argument and requests to be run as administrator. The user is prompted to confirm the action and the restricted script exits leaving the escalated administrator script running. When the user grants permission the elevated argument is found and the script changes back from the %System32% working directory to the script where the script is located.

If WScript.Arguments.Named.Exists(“elevated”) = False Then
‘Launch the script again as administrator
CreateObject(“Shell.Application”).ShellExecute “wscript.exe”, “””” & WScript.ScriptFullName & “”” /elevated”, “”, “runas”, 1
WScript.Quit
Else
‘Change the working directory from the system32 folder back to the script’s folder.
Set oShell = CreateObject(“WScript.Shell”)
oShell.CurrentDirectory = CreateObject(“Scripting.FileSystemObject”).GetParentFolderName(WScript.ScriptFullName)
MsgBox “Now running with elevated permissions”
End If
If WScript.Arguments.Named.Exists("elevated") = False Then
	'Launch the script again as administrator
	CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /elevated", "", "runas", 1
	WScript.Quit
Else
	'Change the working directory from the system32 folder back to the script's folder.
	Set oShell = CreateObject("WScript.Shell")
	oShell.CurrentDirectory = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
	MsgBox "Now running with elevated permissions"
End If