28

Can anyone help me with running vbs from itself but with administrator rights? I need rename computer with Windows 8 via VBScript, but it's possible only if I run my script through administrator command line (CMD → Run as Administrator → runScript.vbs). If I start script with classic CMD the computer isn't renamed.

My idea is I start script with user rights, without parameters and if there is no parameter, the script re-runs itself with admin rights and with parameter as identificator "I'm admin".

Does anyone know how I can do this?

Edit:

I tried this:

If WScript.Arguments.Count = 0 Then
    Set objShell = CreateObject("Shell.Application")
    objShell.ShellExecute "wscript.exe", "c:\Users\admin\Documents\selfConfigure.vbs -1", "", runas", 1
End If
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Daphnis
  • 437
  • 1
  • 5
  • 14
  • check elevation powertoy http://blogs.technet.com/b/elevationpowertoys/archive/2010/06/20/creating-a-self-elevating-script.aspx – Loïc MICHEL Jul 04 '13 at 09:54
  • This is great code, but I think it isn't solution of my problem. My problem isn't get if script is running as admin or not. I need reliably run it as admin. This code is only for check it, I'm right? – Daphnis Jul 04 '13 at 10:58
  • nope "The following script will “re-launch itself” elevated if it is not already running elevated" – Loïc MICHEL Jul 04 '13 at 11:21
  • 1
    The code would elevate the script, but you forgot the quotes before runas. – user4759923 Jun 13 '15 at 05:08

6 Answers6

36

If UAC is enabled on the computer, something like this should work:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

'actual code
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    It is practically the same what I tried. But it's not working. What exactly does enabled UAC mean? I have set it to "Never notify", is that disabled? If I try change UAC to higher option it didn't help. – Daphnis Jul 04 '13 at 10:32
  • "Never notify" on Win8 isn't exactly disabled (you'd have to use policies to disable it entirely), but almost. The code worked fine for me when I re-enabled UAC on my Win7 testbox. Did you reboot after changing the UAC level? – Ansgar Wiechers Jul 04 '13 at 10:44
  • No I didn't, but unfortunately I can't use enabled UAC because this script must worked without user. No user will wait for ask for access. This script is for automatic tests. Isn't other option? :/ – Daphnis Jul 04 '13 at 10:54
  • Can't you just run it as a scheduled task, then? – Ansgar Wiechers Jul 04 '13 at 11:13
  • 1
    Sorry, you right. I didn't quit first script and that made problem. :) Now it goes. – Daphnis Jul 04 '13 at 11:48
9

Add this to the beginning of your file:

Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.Length = 0 Then
  Set ObjShell = CreateObject("Shell.Application")
  ObjShell.ShellExecute "wscript.exe" _
    , """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
  WScript.Quit
End if
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Hussain
  • 276
  • 5
  • 11
3

Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269

Configuring Applications to Always Request Elevated Rights:

Programs can be configured to always request elevation on the user level via registry settings under HKCU. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value" under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" for the full path to an executable with a value of "RUN AS ADMIN". Below is an example for CMD.

Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"
Amit
  • 351
  • 1
  • 2
  • 8
  • 3
    But I need elevated privileges to edit that registry setting in the first place, no? Kind of defeats the purpose. – masterxilo Nov 23 '17 at 21:56
  • https://stackoverflow.com/questions/47895544/mkdir-in-batch-file-as-admin and https://stackoverflow.com/questions/47902221/run-batch-script-as-admin-during-maven-build – CatCat Oct 10 '18 at 19:52
3

fun lil batch file

@set E=ECHO &set S=SET &set CS=CScript //T:3 //nologo %~n0.vbs /REALTIME^>nul^& timeout 1 /NOBREAK^>nul^& del /Q %~n0.vbs&CLS
@%E%off&color 4a&title %~n0&%S%CX=CLS^&EXIT&%S%BS=^>%~n0.vbs&%S%G=GOTO &%S%H=shell&AT>NUL
IF %ERRORLEVEL% EQU 0 (
    %G%2
) ELSE (
    if not "%minimized%"=="" %G%1
)
%S%minimized=true & start /min cmd /C "%~dpnx0"&%CX%
:1
%E%%S%%H%=CreateObject("%H%.Application"):%H%.%H%Execute "%~dpnx0",,"%CD%", "runas", 1:%S%%H%=nothing%BS%&%CS%&%CX%
:2
%E%%~dpnx0 fvcLing admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"& timeout 3 /NOBREAK>nul
:3
%E%x=msgbox("end of line" ,48, "%~n0")%BS%&%CS%&%CX%
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
funny
  • 31
  • 1
  • 2
    @Lizz this is the site that explains it all: https://www.e-learn.cn/content/wangluowenzhang/84740 – DeerSpotter Oct 09 '18 at 20:42
  • I don't know if I'd call that a FUN lil batch file! I think the adage "Code it written once, but read thousands of times" should be applied here. Code is often no good to anyone if it is not easily readable. It seems like there is a lot of room for improvement here in terms of readability. But, seriously, that's just IMVHO. A lot of newer users to cmd files, and vbs files would almost certainly have a very difficult time reading this, and therefore probably shouldn't implement it unless they FULLY understand what it is doing....but I could be wrong too. – LarryF Dec 02 '22 at 18:23
2

`My vbs file path :

D:\QTP Practice\Driver\Testany.vbs'

objShell = CreateObject("Shell.Application")

objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1

set x=createobject("wscript.shell")

wscript.sleep(2000)

x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"

--from google search and some tuning, working for me

rob
  • 2,136
  • 8
  • 29
  • 37
Hari Krishna
  • 181
  • 1
  • 3
2

This is the universal and best solution for this:

If WScript.Arguments.Count <> 1 Then WScript.Quit 1
RunAsAdmin
Main

Sub RunAsAdmin()
    Set Shell = CreateObject("WScript.Shell")
    Set Env = Shell.Environment("VOLATILE")
    If Shell.Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
        Env("CurrentDirectory") = Shell.CurrentDirectory
        ArgsList = ""
        For i = 1 To WScript.Arguments.Count
            ArgsList = ArgsList & """ """ & WScript.Arguments(i - 1)
        Next
        CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & ArgsList & """", , "runas", 5
        WScript.Sleep 100
        Env.Remove("CurrentDirectory")
        WScript.Quit
    End If
    If Env("CurrentDirectory") <> "" Then Shell.CurrentDirectory = Env("CurrentDirectory")
End Sub

Sub Main()
    'Your code here!
End Sub

Advantages:

1) The parameter injection is not possible.
2) The number of arguments does not change after the elevation to administrator and then you can check them before you elevate yourself.
3) You know for real and immediately if the script runs as an administrator. For example, if you call it from a control panel uninstallation entry, the RunAsAdmin function will not run unnecessarily because in that case you are already an administrator. Same thing if you call it from a script already elevated to administrator.
4) The window is kept at its current size and position, as it should be.
5) The current directory doesn't change after obtained administrative privileges.

Disadvantages: Nobody

  • Thank you, your answer help me to answer this [question](https://superuser.com/a/1550926/969781) – Io-oI May 13 '20 at 03:40