Scripting MMC with vbscript - vbscript

I would like to add a snap in via vbscript and I have been having a problem getting the snap in to add to the console. It will be run in a Windows 7 environment. If someone could have a look see and direct me in the right direction I would be most grateful. Thanks.
<code>
'Elevated privileges start
'Start of UAC workaround code
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If WScript.Arguments.length =0 Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
consoleName = "C:\Burnett.msc"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(consoleName) Then
Wscript.Echo "console already exists"
Else
On Error Resume Next
Set objMMC = CreateObject("MMC20.Application")
If err.Number <> 0 Then
Wscript.Echo "an error occurred. unable to create mmc console"
Wscript.Quit(0)
End If
objMMC.Show
Set objDoc = objMMC.Document
objDoc.snapins.add("Local Computer\Non-Administrators")
if err then
'Trap the error just after the statement where an error/exception can occur and handle it elegantly
msgbox("Snap-in Not found")
err.clear
end if
objDoc.ActiveView.StatusBarText = "Pane 1|Pane 2|Pane 3"
objMMC.UserControl = 1
objDoc.Name = consoleName
objDoc.Save()
End If
Set fso = Nothing
End If
</code>

"Local Computer\Non-Administrators" is just a system-supplied description for the particular configuration of a snap-in. In this case, the actual snap-in name is "Group Policy Object Editor". Thus to eliminate the error in the code change
objDoc.snapins.add("Local Computer\Non-Administrators")
to
objDoc.snapins.add("Group Policy Object Editor")
Unfortunately, this will only get you as far as MMC putting up a "Select Group Policy Object" dialog. You will then have to manually select the configuration you need using that dialog. As far as I can tell there is no way to supply Snapins.Add with the parameters to select the local non-admin users.
The code below will fully automate the process of setting up the snap-in. However, its reliance on SendKeys makes it extremely brittle. It worked on my system, but there's a good chance you'll need to modify the sequence of key strokes and/or the timing delays to make it work on your system. And once you get it working, there's no guarantee it will continue to do so as local conditions are mutable and can greatly effect the timing.
option explicit
if WScript.Arguments.Named.Exists("elevated") = false then
'Launch the script again with UAC permissions
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /elevated", "", "runas", 1
WScript.Quit
end if
Dim mmc : set mmc = WScript.CreateObject("MMC20.Application")
mmc.Show
mmc.UserControl = 1 'to keep MMC open
Dim oShell : set oShell = WScript.CreateObject("Wscript.Shell")
oShell.AppActivate "Console1"
WScript.Sleep 200
oShell.SendKeys "%f"
WScript.Sleep 200
oShell.SendKeys "m"
WScript.Sleep 400
oShell.SendKeys "group{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{RIGHT}{TAB}Non{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{TAB}{ENTER}"

Related

Regwrite nonpersistent value in the registry after restart [duplicate]

This question already has answers here:
File checking on Windows Startup is failing [duplicate]
(2 answers)
Closed 2 years ago.
I have this script (below), not the best script but it works fine, however every time I restart my computer that new registry triplet is gone and I have no guess why.
I got no errors from this script, but if I let it run for a reasonably period of time a vbs Msgboxpops up with,
This script contains malicious content and has been blocked by your antivirus software.
I honestly don't think it is related but apparently I cannot post a question being concise due to text requirements limitations. Or is it related and the antivirus is wiping out that triplet? After this message the new register is still there (in the registry) but not after a restart.
Dim sKey
sKey = "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\so_Robocopy"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
If fso.FileExists("so_Robocopy.bat") Then
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & "so_Robocopy.bat" & Chr(34), 0
WScript.Sleep 300000
Loop
Else
RemoveFromRegistry()
End If
Function RemoveFromRegistry()
On Error Resume Next
wshShell.RegDelete sKey 'Error handling routine
End Function
Function RegisterOnWindowsStartUp()
If DoesRegistryExist = False Then
wshShell.RegWrite sKey, Chr(34) & WScript.ScriptFullName & Chr(34), "REG_SZ"
End If
End Function
Function DoesRegistryExist()
with CreateObject("WScript.Shell")
on error resume next
sValue = .regread(sKey)
DoesRegistryExist = (err.number = 0)
on error goto 0
End with
End Function
When you run the script, it will work fine, and no problem because you are running the script on the current directory and the so_Robocopy.bat existed on the same directory.
However, on Windows Startup, the script will execute on the Directory of Windows Startup and not on the original directory where your script is located.
Here's what happened to your code,
' Script execute from the Directory of Windows Starup
If fso.FileExists("so_Robocopy.bat") Then ' (1) There will be no so_Robocopy.bat on the Directory of Windows Startup, then this will return false.
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & "so_Robocopy.bat" & Chr(34), 0
WScript.Sleep 300000
Loop
Else (2) The condition is false, then remove the key from registry.
RemoveFromRegistry()
End If
Make sure you are looking from the original directory where your script is. You can use Scripting.FileSystemObject and WScript.ScriptFullName for that.
(1)
so_robocopy_file = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\so_Robocopy.bat"
If fso.FileExists(so_robocopy_file) Then ' (2)
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & so_robocopy_file & Chr(34), 0 ' (3)
WScript.Sleep 300000
Loop
Else

VBSCRIPT - SWbemObjectSet error 8004100C

I wrote a script to detect when I have a second monitor connected, and to switch Rainmeter layouts accordingly. However, occasionally when I put my computer to sleep, then wake it up, I get the following error:
---------------------------
Windows Script Host
---------------------------
Script: C:\Users\Tim\Documents\Shortcuts\Create\scripting\commandSniffer\detectMonitor.vbs
Line: 12
Char: 2
Error: Not supported
Code: 8004100C
Source: SWbemObjectSet
---------------------------
OK
---------------------------
All I really want to do is keep my script from crashing when I sleep my computer. If there's not an easy fix for this, how can I catch the error in the script and ignore it? Full source code below:
strComputer = "Localhost"
singleMon = "myLayout"
doubleMon = "myLayout(2monitor)"
rainmeterPath = """C:\Program Files\Rainmeter\Rainmeter.exe"" !LoadLayout "
previousState = 1
set wshshell = createobject("wscript.shell")
do
Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\wmi")
Set colItems = objWMI.ExecQuery ("SELECT * FROM WMIMonitorID")
'Wscript.Echo strComputer & " has " & colItems.count & " monitors configured."
if not isnull(colItems) and previousState <> colItems.count then
if colItems.count = 2 then
wshshell.run rainmeterPath & doubleMon,0
else
wshshell.run rainmeterPath & singleMon,0
end if
previousState = colItems.count
else
wscript.sleep 9000
end if
wscript.sleep 1000
loop
On Error Resume Next
transfers error handling from vbscript to you. You now need to test for errors after every call that might cause one.
If err.number <> 0 then
'fix error or ignore
err.clear
'If decide to crash
'err.raise(err.number, blah, blah, blah)
'wscript.Quit
End If
Error handling is a chain. From lowest function call up to the app. Windows looks for error handlers, if it can't find one it crashes. Err.raise allows you to propagate errors up the chain.

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

Set Proxy authentication for ie using Vbscript

I want to auto fill proxy authentication value of username and password for ie using vbscript.
After I added the proxy ip and port to Tools>Internet Option>Connection Tab>LAN Settings. I am prompted with the following dialog
Is there anyways using VBS OR VB to auto fill this ?
So, far i have got the code like so
'begin script
Option Explicit
Dim valUserIn
Dim objShell, RegLocate
Set objShell = WScript.CreateObject("WScript.Shell")
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
WScript.Sleep(1000)
valUserIn = Inputbox("Enter the Proxy server you want to use.","Proxy Server Required","proxygate.mydomain.com:8080")
if valUserIn = "" then
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"0","REG_DWORD"
'MsgBox "No proxy mode"
else
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer"
objShell.RegWrite RegLocate,valUserIn,"REG_SZ"
RegLocate = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyEnable"
objShell.RegWrite RegLocate,"1","REG_DWORD"
'MsgBox "Proxy mode: " & valUserIn
end if
WScript.Quit
'end script
But this only set's the proxy ip and port.
Thanks in advance..
You can utilize the Sendkeys shell command which will type in and activate keyboard commands for you once it has allocated the correct screen. However, this is assuming you are running the script while it is open. If you are looking for something that prefills that data before hand. I'm afraid I cannot assist in that realm.
Dim WshShell, Success
Set WshShell = WScript.CreateObject("WScript.Shell")
'Wait for window to popup....
'if this doesn't activate it directly, try clicking on the window.
Do Until Success = True
Success = objShell.AppActivate("Windows Security")
Wscript.Sleep 1000
Loop
WScript.Sleep 500
WshShell.SendKeys "Username"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "{TAB}" 'tab for password field
WshShell.SendKeys "Password"
wscript.sleep 500 'allow program to have time to type it in.
WshShell.SendKeys "%o" 'Alt + O for hitting "OK"
wscript.sleep 500

How to output Command prompt to a log file using VBScript

I'm not a programmer so I don't want to overly irritate the fine folk in this forum. My issue is that I would like to use VBScript to Telnet into a Linux device, issue a DF command and output all response to a log file which I can parse later. I originally found a method to successfully Telnet but I have have been experimenting without success regarding the text file output requirement. The following code certainly does not work but I am wondering if I am even close to the correct method?
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("cmd /c dir")
WshShell.run"cmd" '*** open command window ***
WScript.Sleep 250
WshShell.SendKeys("{Enter}")
WshShell.SendKeys"telnet 10.13.2.2"
WshShell.SendKeys("{Enter}")
WScript.Sleep 2000
WshShell.SendKeys"root"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
WshShell.SendKeys"password"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("C:\VBSmemSize.txt", 2, True)
WshShell.SendKeys"df /mnt/cf"
WshShell.SendKeys("{Enter}")
Do
strFromProc = oExec.Stdout.Readline()
WScript.Echo strFromProc
Loop While Not objLogFile.StdOut.atEndOfStream
You can capture output from external commands but not at the same time interact with them like you do with sendkeys. Here an example of what works
Function ExecPing(strTarget)
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "antwoord van") Then '"reply from" in E
WScript.Echo VbCrLf & strTarget & " responded to ping."
ExecPing = True
Else
WScript.Echo VbCrLf & strTarget & " did not respond to ping."
ExecPing = False
End If
End Function
ExecPing pcname

Resources