How to create a user account in Windows Vista using VBScript? - windows-vista

How to create a user account in Windows Vista using VBScript?
I'm using the following script. It's working fine on Windows XP, but gives me an error on Windows Vista:
strUserName = "username"
strPassword = "password"
strComputer = "."
set objSystem = GetObject("WinNT://" & strComputer)
set objUser = objSystem.Create("user", strUserName)
objUser.SetPassword strPassword
objUser.SetInfo

I am able to run this script on my Vista box just fine, and it creates the user.
I suspect you might be having a UAC issue. This article provides some options for elevating the permissions of your script.
Option 1 – the code relaunches itself with elevated permissions:
If WScript.Arguments.length = 0 Then
Set objShell = CreateObject("Shell.Application")
'Pass a bogus argument, say [ uac]
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
'Add your code here
End If
Option 2 – a separate launcher script:
Set objShell = CreateObject("Shell.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
strPath = FSO.GetParentFolderName (WScript.ScriptFullName)
If FSO.FileExists(strPath & "\MAIN.VBS") Then
objShell.ShellExecute "wscript.exe", _
Chr(34) & strPath & "\MAIN.VBS" & Chr(34), "", "runas", 1
Else
MsgBox "Script file MAIN.VBS not found"
End If

Related

"dir" parameter in Shell.Execute command doesn't work when "verb" parameter contains "runas" option [duplicate]

I need to copy my file "manufacturer.bmp", wich is located in the same directory as the script (in my flash drive), to the system32 directory.
I succeed, in getting the variables sourcefile, destinationdirectory, and to elevate my script, but when I elevate it, my sourcefile variable is lost, because of the use of CurrentDirectory, which differs in this mode.
Set shell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
sourcefile = fso.buildpath(CurrentDirectory, "manufacturer.bmp")
MsgBox(sourcefile)
'Checks if the script is running elevated (UAC)
Function isElevated
Set shell = CreateObject("WScript.Shell")
Set whoami = shell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
isElevated = True
Else
isElevated = False
End If
End Function
'Re-runs the process prompting for priv elevation on re-run
Sub uacPrompt
'Check if we need to run in C or W script
interpreter = "wscript.exe"
If InStr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
interpreter = "wscript.exe"
Else
interpreter = "cscript.exe"
End If
'Start a new instance with an elevation prompt first
Set shellApp = CreateObject("Shell.Application")
shellApp.ShellExecute interpreter, Chr(34) & WScript.ScriptFullName & _
Chr(34) & " uac", "", "runas", 1
'End the non-elevated instance
WScript.Quit
End Sub
'Make sure we are running elevated, prompt if not
If Not isElevated Then uacPrompt
destinationdir = fso.buildpath(shell.ExpandEnvironmentStrings("%windir%"), _
"system32")
MsgBox(destinationdir)
fso.CopyFile sourcefile, destinationdir
Any idea of how to push my sourcefile var to the child elevated script?
The ShellExecute method allows you to specify the working directory as the 3rd argument, so you can pass the current directory to the elevated script and build the sourcefile path after elevation. Also, your code could be streamlined quite a bit.
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " uac", _
sh.CurrentDirectory, "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Edit: or at least that's how it would work if you weren't elevating the process. According to this blog post from Raymond Chen the start directory is ignored when elevating processes, so that malicious DLLs from the current directory aren't loaded into elevated processes by mistake. Meaning that you must pass the working directory "manually", like this:
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " " & _
Chr(34) & sh.CurrentDirectory & Chr(34), , "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
sh.CurrentDirectory = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Note that since your destination path is a folder, it must have a trailing backslash (as documented).

vbs run program as admin and with a priority level

I want on startup to launch a vbs script that will launch another program as administrator and set the priority of that program to above normal or high priority.
I currently have made it to launch the program as admin but am stuck on setting the process level.
Set app = CreateObject("Shell.Application")
app.ShellExecute """d:\SYNC\Dropbox\PORTABLE_PROGRAMS\ahk\Navigare\KeyboardEnchancer\KeyboardEnchancer.exe""", , , "runas", 3
I edited the answer to address your permission problem, the script now self-elevates to run as administrator, more info at: How to Automatically Elevate a Vbscript to Run it as Administrator?. Tested and working flawlessly on my machine.
If WScript.Arguments.length = 0 Then
Set objShell = CreateObject("Shell.Application")
'Pass a bogus argument, say [ uac]
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
Set objShell= CreateObject("Shell.Application")
strComputer = "."
Const HIGH_PRIORITY = 128
processName = "notepad.exe" ' The process name of your app
appName = "C:\Windows\System32\notepad.exe" ' The app you want to run
objShell.ShellExecute appName, , , "runas", 1
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & processName & "'")
For Each p in colProcesses
p.SetPriority(HIGH_PRIORITY)
Next
End If
More info at: SetPriority method of the Win32_Process class and ShellExecute method.
I used this to change a script's own priority from within its execution:
Sub SetPriority()
Const IDLE = 64, BELOW_NORMAL = 16384, NORMAL = 32, ABOVE_NORMAL = 32768, HIGH_PRIORITY = 128, REAL_TIME = 256
GetObject("winmgmts:\\.\root\CIMV2").ExecQuery("Select * From Win32_Process Where CommandLine Like '%" &Wscript.ScriptName& "%'").ItemIndex(0).SetPriority(HIGH_PRIORITY)
End Sub
Call SetPriority()
This answers the question... as admin with priority.
dim sFile: sFile=chr(34)& "C:\Windows\System32\notepad.exe" &chr(34)
CreateObject("Shell.Application").ShellExecute "cmd.exe","/c START /HIGH /B """" " &sFile, ,"runas", 1

transfer CurrentDirectory from un-elevated script to elevated one

I need to copy my file "manufacturer.bmp", wich is located in the same directory as the script (in my flash drive), to the system32 directory.
I succeed, in getting the variables sourcefile, destinationdirectory, and to elevate my script, but when I elevate it, my sourcefile variable is lost, because of the use of CurrentDirectory, which differs in this mode.
Set shell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
sourcefile = fso.buildpath(CurrentDirectory, "manufacturer.bmp")
MsgBox(sourcefile)
'Checks if the script is running elevated (UAC)
Function isElevated
Set shell = CreateObject("WScript.Shell")
Set whoami = shell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
isElevated = True
Else
isElevated = False
End If
End Function
'Re-runs the process prompting for priv elevation on re-run
Sub uacPrompt
'Check if we need to run in C or W script
interpreter = "wscript.exe"
If InStr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
interpreter = "wscript.exe"
Else
interpreter = "cscript.exe"
End If
'Start a new instance with an elevation prompt first
Set shellApp = CreateObject("Shell.Application")
shellApp.ShellExecute interpreter, Chr(34) & WScript.ScriptFullName & _
Chr(34) & " uac", "", "runas", 1
'End the non-elevated instance
WScript.Quit
End Sub
'Make sure we are running elevated, prompt if not
If Not isElevated Then uacPrompt
destinationdir = fso.buildpath(shell.ExpandEnvironmentStrings("%windir%"), _
"system32")
MsgBox(destinationdir)
fso.CopyFile sourcefile, destinationdir
Any idea of how to push my sourcefile var to the child elevated script?
The ShellExecute method allows you to specify the working directory as the 3rd argument, so you can pass the current directory to the elevated script and build the sourcefile path after elevation. Also, your code could be streamlined quite a bit.
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " uac", _
sh.CurrentDirectory, "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Edit: or at least that's how it would work if you weren't elevating the process. According to this blog post from Raymond Chen the start directory is ignored when elevating processes, so that malicious DLLs from the current directory aren't loaded into elevated processes by mistake. Meaning that you must pass the working directory "manually", like this:
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " " & _
Chr(34) & sh.CurrentDirectory & Chr(34), , "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
sh.CurrentDirectory = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Note that since your destination path is a folder, it must have a trailing backslash (as documented).

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

Script for running a batch file as Administrator without prompting for password

The below script works on Windows XP as expected. The script abc.bat would run as Administrator without a prompt for password(password is supplied automatically). But the same script is not working on our Windows 7 Box. Are there any changes required? I have no experience with VB Scripting. Thanks!
Option Explicit
Const USER = "administrator"
Const PASS = "*********"
Const WSNAME_COMMANDLINE = "C:\support\abc.bat"
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim WSHShell : Set WshShell = CreateObject("WScript.Shell")
Dim WshNetwork : Set WshNetwork = CreateObject("WScript.Network")
Dim oDic : Set oDic = CreateObject("Scripting.Dictionary")
Dim objArgs : Set objArgs = WScript.Arguments
Dim oProcessEnv : Set oProcessEnv = WshShell.Environment("PROCESS")
Dim sPathToRunAs, iReturnCode
sPathToRunAs = oProcessEnv("SystemRoot")&"\System32\runas.exe"
''msgbox sPathtorunas
if Not fso.FileExists(sPathToRunAs) Then : WScript.Quit(1) 'Can't find RunAs
'''msgbox "runas /user:" & USER & " " & CHR(34) & WSNAME_COMMANDLINE & CHR(34)
iReturnCode=WshShell.Run("runas /user:" & USER & " " & CHR(34) & WSNAME_COMMANDLINE & CHR(34), 2, FALSE)
Wscript.Sleep 40 ' Time for window to open.
WshShell.AppActivate(sPathToRunAs)' Activate the Window
Wscript.Sleep 3
WSHShell.SendKeys PASS & "~" ' Send the password
Wscript.Sleep 3
''msgbox "done"
Did you try the script on Windows 7 with UAC (User Account Control) disabled?
You can find a howto on disabling UAC here: http://windows.microsoft.com/en-US/windows-vista/Turn-User-Account-Control-on-or-off
If UAC is the reason for your issue, you may use windows task scheduler to avoid this like it is explained here: http://poundcomment.wordpress.com/2011/03/18/how-to-create-a-whitelist-uac-for-windows-7/

Resources