[windows] How to run vbs as administrator from vbs?

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

This question is related to windows vbscript administrator elevated-privileges

The answer is


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


`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


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"

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

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%

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to vbscript

How to run VBScript from command line without Cscript/Wscript How to set recurring schedule for xlsm file using Windows Task Scheduler How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31') How do I rename a file using VBScript? How to get two or more commands together into a batch file How to run vbs as administrator from vbs? Find specific string in a text file with VBS script Getting current directory in VBScript Run Command Line & Command From VBS Permission denied on CopyFile in VBS

Examples related to administrator

Google Chrome: This setting is enforced by your administrator How to run vbs as administrator from vbs? Batch Script to Run as Administrator How do I run a program from command prompt as a different user and as an admin What precisely does 'Run as administrator' do? Running a command as Administrator using PowerShell? How do I set a Windows scheduled task to run in the background? Start / Stop a Windows Service from a non-Administrator user account How do I force my .NET application to run as administrator? Psexec "run as (remote) admin"

Examples related to elevated-privileges

How to run python script with elevated privilege on windows How to run vbs as administrator from vbs? How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required? How do I force my .NET application to run as administrator? How to request Administrator access inside a batch file