How do I specify “Run with highest privileges” in VBScript? - vbscript

When I use the GUI Task Scheduler, I can easily check the "Run with highest privileges" checkbox.
I found no such option in the VBScript command line too, however.
Is there a way to do that from the VBScript?
How to add this script this two feature?
Example VBScript: http://msdn.microsoft.com/en-us/library/aa383665%28v%3DVS.85%29.aspx
Privileges: http://msdn.microsoft.com/en-us/library/windows/desktop/aa382076%28v=vs.85%29.aspx

This VBScript code automates the SchTasks.exe program and should demonstrate what you want to do. To get a list of the switches for creating tasks with SchTasks, you can run this:
schtasks.exe /create /?
You still have to run the below script from an administrative command-prompt to be able to create a task with "Highest" privileges. Also, if you wish to use an account other than the system account, you should use the /RP switch. If you're fully automating it, you may wish to use the /F switch as well to force overwriting an existing task. Otherwise it may hang while waiting for user input.
Option Explicit
Dim WshShell, strWinDir, strCmdLine, lngExitCode
Const OpenAsCurrentWindowIsOpened = 10, WaitForExit = True
Set WshShell = CreateObject("WScript.Shell")
strWinDir = WshShell.ExpandEnvironmentStrings("%WINDIR%")
strCmdLine = strWinDir & "\System32\SCHTASKS.exe /create /SC DAILY /TN ""My VBScript Task"" /TR """ & strWinDir & "\System32\calc.exe"" /RL HIGHEST /RU ""NT AUTHORITY\SYSTEM"""
lngExitCode = WshShell.Run(strCmdLine, OpenAsCurrentWindowIsOpened, WaitForExit)
If lngExitCode = 0 Then
WScript.Echo "Success"
Else
WScript.Echo "Failed with error code " & CStr(lngExitCode)
End If

If you're asking how to interactively run VBScripts in admin mode, you just have to run CSCRIPT from a command-line that is already running in "Admin mode". For example, click Start, type cmd, wait a few seconds..., right-click cmd.exe and choose "Run as Administrator". Then when you run CSCRIPT from that command-line it will run with highest privileges already. Note you have to be logged-in with an admin user account already.
Or are you asking how you automate creating new scheduled tasks in VBScript with those options set?

If you're referring to admin mode, try this:
Dim ObjShell
Set ObjShell = CreateObject("WScript.Shell")
ObjShell.Run "runas.exe"
Since CMD in Admin mode is just runas.exe, you can run it through WScript.Shell(ObjShell.Run).
This way is more effecient because if you want to run a command line you can simply do this:
ObjShell.Run "runas.exe /K (command goes here)"

Related

How to get a VBS script to start a service if it is stopped, with no window?

I have a scheduled task that launched a .vbs file, that launches a batch file with no window, that checks to see if a service is running and if not, then it starts it. The reason I have a .vbs launching the batch file is so the batch file doesn't have the window pop up. The issue I am having is that I get access denied when I run the batch via .vbs, so I want to run the whole system in a .vbs script to check to see if a service is started or running and if not start it. Also I used the schtasks to to run the .vbs with /RL Highest so I do not get access denied, but when the .vbs launches the batch file, the batch files does not have the permission and get access denied.
The scheduled task command I entered:
schtasks /CREATE /TN "OpenTunnel" /TR "C:\BTools\OpenTunnel\Invisable_OpenTunnel.vbs" /sc minute /mo 10 /RU ***** /RP ***** /RL HIGHEST
And here is the batch file that runs and checks the service state.
for /F "tokens=3 delims=: " %%H in ('sc query "Hamachi2Svc" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
net start "Hamachi2Svc"
)
)
And here is the code of the .vbs that lanches the batch with no window:
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "opentunnel.bat" & Chr(34),0
Set WinScriptHost = Nothing
So it works if I run the batch as an administrator, but is there a way to have a .vbs run every 10 min that does something similar that the batch file does? A .vbs file would be the best after all, I can grant it /RL with HIGHEST and that should work.
Thanks in advance =)
Use WMI (specifically the Win32_Service class) for this:
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Service WHERE Name = 'Hamachi2Svc'"
For Each svc In wmi.ExecQuery(qry)
If svc.State <> "Running" Then svc.StartService
Next

Would you fix this vbs to execute this bat file with admin priviledge

Under windows 7 with uac activated.
This is all around an issue. THIS ISSUE:
upnphost excessive cpu load
Especifically:
Mine has this problem frequently, and I hate to go restart the upnphost service all the time, so instead i just created a task in the
task scheduler to run a once a day, and repeat every 5 minutes. The
task runs a .bat file:
net stop upnphost
net start upnphost
if you want to make it run in the background without the cmd window
coming up, run this .vbs with the above .bat already created as
"C:\upnphost.bat":
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\upnphost.bat" & Chr(34), 0 Set
WshShell = Nothing
this way the upnphost service will automatically restart every 5
minutes with no visible presentation, so if it decides to misbehave
and go high cpu, it will be for 5 minutes tops, you could change this
to any interval you want.
Everything works except for the fact that for the bat to actually work i need to right click directly on the bat and execute as admin.
For that reason if i click the vbs it will execute it but not as admin and it wont work.
So scheduling it as a task wont work either.
Can you fix the code in the vbs:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\upnphost.bat" & Chr(34), 0 Set
WshShell = Nothing
So it executes the bat with admin priviledge.
It that matters, my route to the bat has spaces.
Respectfully
You can launch an program as an administrator with UAC enabled, but you'll still get prompted whether you want to launch this program. For example,
Set objSA = CreateObject ("Shell.Application")
objSA.ShellExecute "cmd.exe","uac","","runas",1
However,
I was able to use this vbscript to stop and restart this service using a scheduled task, setting the task to run as "Hidden" and run with the highest privileges.
strService = "upnphost"
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colService = objWMIService.ExecQuery("SELECT Name FROM Win32_Service " _
& "where Name='" & strService & "'")
For Each objService In colService
return = objService.StopService()
return = objService.StartService()
Next
The scheduled task must be run as a user who can start and stop the service (usually an admin account) and with the option "Run with highest privileges" enabled.

Is is possible to have RUN AS prompt for vbscript?

I have this vbscript which changes the registry values and i want it to be able to run as another account(with admin rights) in a standard windows user account. Is it possible to code it such that when u double click on the vbscript, it will ask for yr windows account name and password then u be able to run the script with that account rights?
Thanks!
In the old days you could add a runas key to the respective file type in the registry:
reg add "HKCR\VBSFile\Shell\runas\Command" /ve /t REG_EXPAND_SZ ^
/d "\"%"SystemRoot"%\system32\wscript.exe\" \"%1\" %*" /f
which would add a Run as… entry to the context menu that would prompt you for credentials.
Unfortunately, Microsoft changed the "runas" behavior when they introduced UAC. Now the registry key adds a Run as Administrator entry to the context menu, that will work only with UAC enabled.
Sysinternals to the rescue (as always): you can re-enable the context menu entry for running as a different user with ShellRunas. Download the archive, unzip the executable to a directory in your %PATH% and run ShellRunas.exe /reg to register the program. That will add a Run as different user… context menu entry for executables only, though. To add this entry for VBScript files as well you need to add the relevant registry keys/values yourself, e.g. like this:
reg add "HKCR\VBSFile\Shell\runasuser" /ve /t REG_SZ /d "#shell32.dll,-50944" /f
reg add "HKCR\VBSFile\Shell\runasuser\command" /v DelegateExecute /t REG_SZ ^
/d "{ea72d00e-4960-42fa-ba92-7792a7944c1d}" /f
or by merging a .reg file like this:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\VBSFile\Shell\runasuser]
#="#shell32.dll,-50944"
[HKEY_CLASSES_ROOT\VBSFile\Shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"
There is no elegant way for incorporating this in a VBScript, though. If your system has UAC enabled, you could check if your user already has admin privileges (verification method adopted from here) and otherwise re-launch the script using the ShellExecute method with the "runas" verb:
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
rc = reg.GetStringValue(&h80000003, "S-1-5-19\Environment", "TEMP", val)
If rc = 5 Then
'return code 5 == access denied
're-launch script only when it was run without arguments, so we don't go
'in circles when admin privileges can't be acquired
If WScript.Arguments.Count = 0 Then
're-launch as administrator; the additional argument is a guard to make
'sure the script is re-launched only once
CreateObject("Shell.Application").ShellExecute "wscript.exe" _
, Chr(34) & WScript.ScriptFullName & Chr(34) & " relaunch", "", "runas", 1
WScript.Quit 0
Else
WScript.Echo "Cannot acquire admin privileges."
WScript.Quit 1
End If
Else
'your code here
End If
With UAC disabled, you'd need to prompt for credentials via InputBox (bad) or with a custom password dialog (better). Either way, you'd need to re-launch the script via runas.exe
Set sh = CreateObject("WScript.Shell")
sh.Run "runas /user:" & username & " cscript """ & WScript.ScriptFullName & """"
and type in the password via SendKeys (which is a bad idea in its own right).

VBScript- Single line as administrator

Is it possible to use the shell.run command to run the specified program as an administrator?
for instance:
shell.run(cmd.exe) <---Run this as admin
shell.run(Notepad) <---Run this as normal
I know i can execute the script to run as admin but that means everything inside that script is executed as an administrator.
My other option was to seperate the scripts and run one as admin and include what needs to be ran as admin in that script, then call another script to run and run that one as normal.
Set oShell = CreateObject("Shell.Application")
oShell.ShellExecute "cmd.exe", , , "runas", 1
oShell.Run "nodepad.exe"
(Source: http://social.technet.microsoft.com/Forums/eu/ITCG/thread/310e57f9-2367-4293-9f97-53d0e077aacc)
(More Info: http://ss64.com/vb/shellexecute.html)
Windows (from XP through to Win7 at least) has a runas command which does what you need. See here for details.
So, instead of running cmd.exe, you would run runas.exe, giving cmd.exe as the program to run.
Try this:
Dim ObjShell
Set ObjShell = CreateObject ("WScript.Shell")
ObjShell.Run "runas /K (command goes here) "
ObjShell.Run "notepad.exe"

Windows script - run silent but wait for completion / return right code

Here's my situation:
I have a BAT file that takes a long time to run (1minute to 70 minutes)
I schedule it with Windows scheduler to run every 10 minutes
If it schedules again while it is still running, nothing happens (this is good)
My problem is that I need my BAT to run silently, and it doesn't. So, I want to launch it with a Windows script like the following:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Batch Files\syncfiles.bat" & Chr(34), 0
Set WshShell = Nothing
Unfortunately, when I schedule this script, it does the job but returns instantly, making Windows scheduler think the task is finished when in reality the BAT is just running off by itself somewhere.
Because of this, Windows will reschedule the job again 10 minutes later and make multiple run.
What I need:
Is there a way to tell the Windows script file to wait for the target of the .Run command to complete before progressing/exiting? Basically, I want it to act like I launched another thread and then called join on it, so it does the same thing the BAT would have, but without displaying the console window.
Other Solutions
Tell me any other way to get this BAT to execute silently (powershell commands, whatever) and I'll accept it as a solution as well. Just don't tell me to write a full on C++/C# appliation around it, that's overkill :)
Running: Windows Server 2008 R2
I think all you need is TRUE for the optional 3rd argument
WshShell.Run chr(34) & "C:\Batch Files\syncfiles.bat" & Chr(34), 0, TRUE
Here goes the madness...
Create a file invisible.vbs:
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, True
Then in the task scheduler, call your script like this:
wscript.exe "C:\Batch Files\invisible.vbs" "C:\Batch Files\syncfiles.bat"
I tested it and this does really work: No command window, and the task is considered running until the batch script ends.
Credit goes to https://superuser.com/a/62646/40362.
For 2008 R2 make invisible.vbs have this content, and just execute it directly. It will run the BAT silently and wait for completion.
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "D:\IUpdateScript.bat", 0, true

Resources