Invalid Root in Registry Key (VBScript) - vbscript

i have made a simple VBScript file that enables Task Manager.
but when i execute it , i get error "Invalid Root In Registry Key"
why?
set Shell=CreateObject("Wscript.Shell")
shell.regwrite "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Microsoft\Windows\System\DisableTaskMgr","0","REG_DWORD"

Add this to your code below WScript.Shell:
RunAsAdmin()
Function RunAsAdmin()
If WScript.Arguments.length = 0 Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" & " RunAsAdministrator",,"runas", 1
WScript.Quit
End If
End Function
This will run the script as admin. If it does not work then check your registry path because it is probably incorrect.

Related

Run Wscript.Shell Object to call Administrative Command Prompt for PsExec [duplicate]

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
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
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%
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"
`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
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

Script to display a pop-up and then kills a windows process

I'm trying to deploy an application through SCCM 2012 for Windows7 (x86 and x64) that requires to notify the user that his Microsoft Outlook should be closed before to continue with the installation. It could be either with a Timer or a (Yes / No) choice, then if the user press Yes then it will close Outlook and will continue with the installation otherwise it will send a log file saying the the user cancelled the installation but it can be retried at any time.
So far I just have the installation script that works only to install the applications using a command line script. So, it will just execute some MSI's installations and Windows updates, and then it quits.
The script I have that creates the pop up and that can be called by my CMD file is the following VBScript and was taken from a TechNet article.
Const TIMEOUT = 7
Set objShell = WScript.CreateObject("WScript.Shell")
Set objFS = WScript.CreateObject("Scripting.FileSystemObject")
strPath = Wscript.FullName
strFileVersion = objFS.GetFileVersion(strPath)
iRetVal = objShell.Popup(Wscript.FullName & vbCrLf & _
"File Version: " & _
strFileVersion & vbCrLf & _
"Would you like to close Outlook application and continue with the installation?" _
,TIMEOUT,"Outlook Validation",vbYesNo + vbQuestion)
Select Case iRetVal
Case vbYes
Set objFile = objFS.GetFile(strPath)
objShell.Popup WScript.FullName & vbCrLf & vbCrLf & _
"File Version: " & strFileVersion & vbCrLf & _
"File Size: " & Round((objFile.Size/1024),2) & _
" KB" & vbCrLf & _
"Date Created: " & objFile.DateCreated & vbCrLf & _
"Date Last Modified: " & objFile.DateLastModified & _
vbCrLf,TIMEOUT
Wscript.Quit
Case vbNo
Wscript.Quit
Case -1
WScript.StdOut.WriteLine "Popup timed out."
Wscript.Quit
End Select
So I don't know if there's any useful example that I can use and customize it from there. I'm clueless, blindfolded, I don't see the light. Well you understand my frustration.
Any ideas, examples or links will be really appreciated!!
Thanks & kind regards.
Joel.
This is one way.
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.name & " " & objItem.CommandLine
If LCase(objItem.name) = "outlook.exe" then
If Msgbox("Close Outlook", 33, "Install") = 1 then
objItem.terminate
End If
End If
Next
VBScript's Help file - https://www.microsoft.com/en-au/download/details.aspx?id=2764
For help with the WMI object use wmic at the command prompt.
wmic process get /? (same as wmic path win32_process get /?) and wmic process call /? list properties and methods.
Here my procedure which closes outlook before modifying the profile.
Is is part of a logon script. The show is a logging and informing procedure.
sub CloseOutlook
on error resume next 'to be able to log and continue
dim objWMIService, colProcessList, objProcess, sResult, oShell
set oShell = WScript.CreateObject("WScript.Shell")
set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'OUTLOOK.EXE'")
for Each objProcess in colProcessList
show "outlook is being closed"
objProcess.Terminate()
if Err <> 0 then
show "Error while closing outlook: " & err.Description
end if
sResult = oShell.Popup("Outlook is being closed, profile is configured")
next
end sub
If you want confirmation from the user you will have to use a MsgBox instead.
I'd recommend not faffing about with warnings and closing Outlook, but instead configure the advert to run when no users are logged in. Less chance for problems or accidentally miss-clicked "oh no you lost my emails" situations.

Running a VBS script elevated to get remote computer serial number

Ok, I have an error someplace in here, but not sure where. I am NOT a coder by any means, this is something I have put together from a couple of different sources. This code works, however it seems to run once as a normal user and once at elevated permissions... I just need it to run just once at elevated permissions.
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
End if
On Error Resume Next
Dim System
if Wscript.Arguments.Count >0 then
sSystem=Wscript.Arguments(0)
end if
ComputerName = InputBox("Enter the name of the computer you wish to query")
winmgmt1 = "winmgmts:{impersonationLevel=impersonate}!//"& ComputerName &""
Set SNSet = GetObject( winmgmt1 ).InstancesOf ("Win32_BIOS")
for each SN in SNSet
MsgBox "The serial number for the specified computer is: " & SN.SerialNumber
next
This is the part that re-runs your script with elevated privileges by using the Shell.ShellExecute method with the "runas" verb:
If WScript.Arguments.length = 0 Then
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" &_
" RunAsAdministrator", , "runas", 1
End if
Re-running the script with the additional parameter RunAsAdministrator makes sure that the re-run script skips the above part (since WScript.Arguments.Length is greater than 0 due to that parameter) and goes directly to the "worker" code.
However, the above code snippet doesn't exit after re-running the script, so both the elevated and the original invocation are executing the worker code.
Add a WScript.Quit statement to your code to make the original invocation exit right after re-running itself with elevated permissions and the issue will disappear:
If WScript.Arguments.Length = 0 Then
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", _
"""" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
WScript.Quit 0
End If
that's all (for remote computer):
ComputerName = InputBox("Enter the name of the computer you wish to query")
winmgmt1 = "winmgmts:(impersonationLevel=impersonate}!//"& ComputerName &"\root\cimv2")
Set SNSet = winmgmt1.ExecQuery("Select * from Win32_BIOS")
for each SN in SNSet
MsgBox "The serial number for the specified computer is: " & SN.SerialNumber
next

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
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
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%
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"
`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
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

Error: "Invalid root in registry key" with Shell.RegWrite

When running this code:
CreateObject("WScript.Shell").RegWrite "HKLM\Whatever\", "MyValue", "REG_SZ"
I have problems with .RegWrite only on Windows 8 where I get the error:
"Invalid root in registry key".
Well, with so unhelpful error description I need to do some tests to find out that it was permission issue. However, elevate the script solve this. And to make this real answer I should post what I done, right?
Call ElevateUAC
' ---------------------------
' my duty task goes here...
' ---------------------------
Sub ElevateUAC
If Not WScript.Arguments.Named.Exists("elevated") Then
'Launch the script again as administrator
With CreateObject("Shell.Application")
.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """ /elevated", "", "runas", 1
WScript.Quit
End With
End If
End Sub

Resources