VBScript Read XML File – How To???
So you have an XML file and you want to use it with VBSCript....
In this post we will review reading an XML file by knowing the TAG names, next time we will break down on opening an XML file without knowing the tags.
Let's take a look at this xml file (if you don't know what's XML then go here linky).
I have multiple tags with values, if you know the XML tag
<?xml version='1.0' encoding='UTF-8'?>
<!-- This document was created with Syntext Serna Free. --><YeshaiUpgrade xmlns="Yeshai Upgrade Package">
<Upgrade>
<Version>
<FirstPackage>Yes</FirstPackage>
<UpgradeType>YeshaiMainComp</UpgradeType>
<NewVersion>Yeshai.57</NewVersion>
<OldVersion>Yeshai.50</OldVersion>
<UpgradeBaseFolder>C:\Yeshai</UpgradeBaseFolder>
<Reboot>No</Reboot>
<ExecuteEndSciprt>Upgrade.vbs</ExecuteEndSciprt>
<ShutDownServices>Yes</ShutDownServices>
<ShutDownXMLFile>SomeFile.XML</ShutDownXMLFile>
<ExecuteAfterReboot>Yes</ExecuteAfterReboot>
<ExecuteAfterRebootScript>Phase2.vbs</ExecuteAfterRebootScript>
<Notes>Just Some Notes About The Package</Notes>
</Version>
</Upgrade>
</YeshaiUpgrade>
First thing we need to reference the XML object
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
now we are going to make a reference to our XML file
You can set this how ever you want but I'm going based on the fact I don't know the path to where the file will be (this is not mandatory)
sPackageFile = sCurPath & "\UpgradePackage.xml"
Next step is referencing each and every tag you want to pull from the XML file
FirstPackage = XMLRead (sPackageFile,"FirstPackage") UpgradeType = XMLRead (sPackageFile,"UpgradeType") NewVersion = XMLRead (sPackageFile,"NewVersion") OldVersion = XMLRead (sPackageFile,"OldVersion") UpgradeBaseFolder = XMLRead (sPackageFile,"UpgradeBaseFolder") Reboot = XMLRead (sPackageFile,"Reboot") ExecuteEndSciprt = XMLRead (sPackageFile,"ExecuteEndSciprt") ShutDownServices = XMLRead (sPackageFile,"ShutDownServices") ShutDownXMLFile = XMLRead (sPackageFile,"ShutDownXMLFile") ExecuteAfterReboot = XMLRead (sPackageFile,"ExecuteAfterReboot") ExecuteAfterRebootScript = XMLRead (sPackageFile,"ExecuteAfterRebootScript") Notes = XMLRead (sPackageFile,"Notes")
Now I love functions so just for y'all I've added this function
Function XMLRead(XMLFileName, XMLTag) xmlDoc.load(XMLFileName) Set ElemList = xmlDoc.getElementsByTagName(XMLTag) XMLRead = ElemList.item(0).Text End Function
After you run the process each one of the values is read from the XML file...
Quite simple
Print This Post
Modify Text/Batch/Registry Files For Automation
So let's say you are working with Batch Files or Regsitry files and you want to automate so sort of process to prompt a user for an input box and change values.
We have a registry file that contains the following information that we want to change.
Make sure that you set the text you want to change to strings that aren't anywhere else in the file or else you will make changes to multiple items so don't just change a "Y" to something else.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\YeshaiB]
"SiteID"="XXXX"
"PhoneNumber"="PPP-PPP-PPPP"
"TerminalID"="TID"
First we will start with a input box for SiteID, PhoneNumber and TerminalID
set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
SiteID = InputBox("Please Enter SiteID", "Site ID","")
PhoneNumber = InputBox("Please Enter PhoneNumber in the following format xxx-xxx-xxxx","Phone Number","xxx-xxx-xxxx")
TerminalID = InputBox("Please Enter TerminalID","Terminal ID","")
You can add protection around the input boxes so you have to enter a minimum amount of characters or must be numeric and have a specific amount of digits if you need.
This would be easier to accomplish by specific functions but let's talk about that some other time.
Now let's update our registry file before we merge it or deploy it.
First we point to our registry file
File = "C:\yeshaib.reg"
Now we will open the file and read the content, look for specifc strings and replace them.
Const ForReading = 1 Set objFile = objFSO.OpenTextFile(File, ForReading) MyString = objFile.ReadAll() objFile.Close MyString = Replace(MyString, "PPP-PPP-PPPP", PhoneNumber, 1, -1, 1) MyString = Replace(MyString, "XXXX", SiteID, 1, -1, 1) MyString = Replace(MyString, "TID", TerminalID, 1, -1, 1) Set objFile = objFSO.CreateTextFile( File, True) objFile.Write MyString objFile.Close
Run the script and it will prompt you three times



And the Registy file will have the correct changes
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\YeshaiB] "SiteID"="8192" "PhoneNumber"="972-972-9972" "TerminalID"="4"
Print This Post
Changing Computers IP Addresses with VBScript
So now that we changed the machine name and user names we might need to change some IP's....
As you can see below you will need to specify the IP's somehow (hard coded right now) with a MSGBOX, Registry read, text file, Machine name etc
'----------------------------------------------------------------------
const HKLM = &H80000002
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oNetwork = CreateObject("WScript.Network")
strCurrentComputerName = oNetwork.ComputerName
'Setup IP's you want to implament, you can add logic for MSGBOX etc.
strComputer = "."
IPAddress = "10.11.12.13"
dGateway = "10.11.12.11"
arrIPAddress = Array(IPAddress)
arrSubnetMask = Array("255.255.255.128")
arrGateway = Array(dGateway)
arrDNSServers = Array("12.107.200.146")
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNetAdapters = objWMIService.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
For Each objNetAdapter in colNetAdapters
errEnableStatic = objNetAdapter.EnableStatic(arrIPAddress, arrSubnetMask)
errGateways = objNetAdapter.SetGateways(arrGateway)
intSetDNSServers = objNetAdapter.SetDNSServerSearchOrder(arrDNSServers)
Next
If intSetDNSServers = 0 Then
MSGBOX("Server IPs set to: IPAddress = " & IPAddress)
Else
MSGBOX("Error setting server info.")
End If
Print This Post
Rename Machine Name with VBS
So... we renamed a user name with VBS here - Linky but now we need to change the machine name.
How simple is that? very
As you can see below specify a machine name under
strNewName = "InRimServer"
So "InRimServer" is the hard coded name of the script but you can change this with a MSGBOX or pull the value from other locations....
And initiate a reboot in the end of the script (or manually afterwards)
'----------------------------------------------------------------------
const HKLM = &H80000002
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oNetwork = CreateObject("WScript.Network")
strCurrentComputerName = oNetwork.ComputerName
strNewName = "InRimServer"
strKeyPath = "System\CurrentControlSet\Control\ComputerName\ComputerName"
set objReg = GetObject("winmgmts:\\" & strCurrentComputerName & "\root\default:StdRegProv")
intRC = objReg.SetStringValue(HKLM, strKeyPath, "ComputerName", strNewName)
if intRC <> 0 Then
MSGBOX("Error setting ComputerName value: " & intRC)
Else
MSGBOX("Successfully set ComputerName value to " & strNewName)
end if
strKeyPath = "System\CurrentControlSet\Services\Tcpip\Parameters"
intRC = objReg.SetStringValue(HKLM, strKeyPath, "NV Hostname", strNewName)
if intRC <> 0 Then
MsgBox("Error setting NV Hostname value: " & intRC)
Else
MsgBox("Successfully set NV Hostname value to " & strNewName)
end if
'Remove the comments if you want an auto reboot
' MsgBox("Rebooting system...")
' WScript.Echo "Rebooting system..."
' Set OpSysSet = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}//" & strComputer).ExecQuery("select * from Win32_OperatingSystem where Primary=true")
' for each OpSys in OpSysSet
' OpSys.Reboot()
' Next
Print This Post
Rename Users with VBScript
This question came through the red phone line (well email).... (and there were two questions but I'll save the other for a different post....)
And it's quite simple but we are going to cheat here and use a net user command.
So we need to determine a few things well just one thing, Is the user name constant name or does it change?
So this is how my script would look like
I'm going to look at this as if the user is a constant user (name does not change)
' Set some objects
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
'get our constant user name from the system (change the UserNameHere)
Set colItems = objWMIService.ExecQuery ("Select * from Win32_UserAccount Where Name = 'UserNameHere'")
For Each objItem in colItems
objItem.Rename "NewUserNameHere"
next
'change the user name
WshShell.Run "cmd /c net user UserNameHere /fullname: NewUserNameHere", 1, true
Kinda simple, but what happens if you don't know the user name and simply want to change the user name?
I don't think this is a good idea but lets say we just want to add some characters to the user...
So we are going to add a few lines and change a few lines...
' Set some objects
Set WshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
'set and get the current user account
Set objNetwork = CreateObject("WScript.Network")
strUserName = objNetwork.UserName
'get our constant user name from the system remember we got the current user before
Set colItems = objWMIService.ExecQuery ("Select * from Win32_UserAccount Where Name = '" & strUserName & "'")
For Each objItem in colItems
objItem.Rename strUserName & "Tech"
next
'change the user name
WshShell.Run "cmd /c net user "& strUserName &" /fullname: """ & strUserName & "Tech""", 1, true
MsgBox "cmd /c net user "& strUserName &" /fullname: " & strUserName & "Tech"
Don't forget to add some protection and logging, and if you need to change your auto login etc...
As well you might not need the MsgBox and you will need to reboot.
Print This Post
VBScripts – Generic Templates for download
Hello Readers,
I've added a download section where I will provide templates for Generic Scripts that you can modify and use.
No Credit needed simply enjoy.
Hit the Download section on the top.
Have fun with this one
Set wshShell = wscript.CreateObject("WScript.Shell")
do
wscript.sleep 100
CreateObject("SAPI.SpVoice").Speak "You don't need to see my identification... Join the Droid... "
Loop
Print This Post
To DIM or not to DIM that is the question, VBScript Variables
So I got an email from someone asking me based on the code snippets I place on my site why don't I "Option Explicit" and declare my variables....
So what are variables and what do you do with them?
I'm not going to write to much but pull from another location - Source
Do you remember algebra from school? x=5, y=6, z=x+y
Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).
So now that you know what variables are, let's talk about variable type's in VBScript's and why I don't use them...
In VBScript, all variables are of type variant, that can store different types of data, unlike other languages like VB that you need to declare the variable type like Integer, Decimal etc
You can declare variables in VBScript by starting you code with
Option Explicit Dim MySpaceShip MySpaceShip = "Some Odd Name or Value"
So in VB you would need to declare what your variable would hold something like
Dim MySpaceShip As String ' --> While string can be any value of characters and numbers.... Dim MySpaceShipSpeed As Integer ' --> My Space Ship's speed can only be in number values.....
There are more values but I won't get into that as I said VBScript variables are always variant's that can hold any value numeric or alphanumeric.
Some Rules
A variable can have a short name, something like Y would work but you should put some more details, let's say MySpaceShip.
Rules for VBScript variable names:
They have to begin with a letter!
The varicable cannot contain a period ".", the value they hold can
Length max is only 255 long
So back to VBScript and DIMing......
Why don't I? the answer is quite simple, I create all scripts with VBS Edit and I don't feel the need to declare anything (problems will start if you try to use the same variable twice without doing something with the old value)
So here is a good example of DIMing with and issue
'----------------------------------------------------------------------
' Yeshai Bouskila - Some Script
'----------------------------------------------------------------------
set objShell = CreateObject("Wscript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
'----------------------------------------------------------------------
' Some Variables for Date, Year TOD
D = Day(Date)
Y = Year(Date)-2000
T = Hour(Time) & Minute(Time)
WScript.Echo(Y)
WScript.Echo(T)
Y = "Yeshai"
T = "What???"
WScript.Echo(Y)
WScript.Echo(T)
So as you can see above I've used my Y and T variable's twice.... first time they had my Year and Time value and second time they got the values I assigned to them, Yeshai and What???
Here is my quick test output screen
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
11
2255
Yeshai
What???
***** script completed - exit code: 0 *****
Now in a real world you would write it like so:
Option Explicit
'----------------------------------------------------------------------
' Yeshai Bouskila - Some Script
'----------------------------------------------------------------------
set objShell = CreateObject("Wscript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
'----------------------------------------------------------------------
' Some Variables for Date, Year TOD
Dim D, Y, T
D = Day(Date)
Y = Year(Date)-2000
T = Hour(Time) & Minute(Time)
WScript.Echo(Y)
WScript.Echo(T)
Dim Y,T
Y = "Yeshai"
T = "What???"
WScript.Echo(Y)
WScript.Echo(T)
And the error would be "Testing.vbs(19, 6) Microsoft VBScript compilation error: Name redefined" (From my output box of VBS Edit) but you would get the same error if you run the file.
So bottom line here do what ever you want to do, one persons best practice is not always the right way, an you don't have to listen to me as i'm not a real developer but do this both for fun and work....
Print This Post
VBScript – In the beginning LOGGING
So what is VBScript? I'm not going to go into the whole what and why... you can read it all on WiKiPeDiA.
Sort Story
VBScript (Visual Basic Scripting Edition) is an Active Scripting language developed by Microsoft that is modelled on Visual Basic. It is designed as a “lightweight” language with a fast interpreter for use in a wide variety of Microsoft environments. VBScript uses the Component Object Model to access elements of the environment within which it is running; for example, the FileSystemObject (FSO) is used to create, read, update and delete files.
Read more on Wiki - http://en.wikipedia.org/wiki/VBScript
So now they what we can do with it and why as there are other solutions.
What did I use VBS for?
Anything from Go-Live with user intervention to enter details for Machine name changes, IP Changes, Registry Changes, DB Changes and much more to automate Go-Live and System staging.
Automate backup and restore, tie into active solutions via MS solutions...
HTA files are a nice touch to make everything look somewhat up to date.
VBScript is a simple but sofisticated way of automating enviromentatal solutions.
But before I start with anything i'm going to recommend LOGGING!!! so add the following code to the end of your scripts and LOG away.
There are many variations but I like the following one and it does have some variations, but here is what I like about it.
1. Create a few log files with the same SUB
2. Consistency with all your log files
In this example we use one log and one line, the log write line
WriteToLog("Generic Log.vbs - Write This")
The output line in the log file will be
8/16/2010 11:26:00 PM : Generic Log : Generic Log.vbs - Write This
Full Code
'----------------------------------------------------------------------
' Filename: Generic Log.vbs
' Copyright (c) Yeshai Bouskila 2009
' All Rights Reserved
'
' Please Enter Updates with date and name including line of Change
'----------------------------------------------------------------------
'----------------------------------------------------------------------
set objShell = CreateObject("Wscript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
'--- Main Begins ---------------------------------------
WriteToLog("Generic Log.vbs - Write This")
'--- Main Ends -----------------------------------------
'--- Write to log --------------------------------------
Sub WriteToLog(strLogMessage)
Const ForAppending = 8
Const vbsName = "Generic Log"
strLogFileName = "C:\GenericLog.log"
strLogEntryTime = NOW
'test whether file exists To either write/append to file
if objFSO.FileExists(strLogFileName) Then
Set objLogFileTransaction = objFSO.OpenTextFile(strLogFileName, ForAppending)
Else
Set objLogFileTransaction = objFSO.CreateTextFile(strLogFileName)
End if
objLogFileTransaction.WriteLine strLogEntryTime & chr(9) & chr(58) & chr(9) & vbsName & chr(9) & chr(58) & chr(9) & strLogMessage
objLogFileTransaction.Close
WScript.StdOut.WriteLine strLogMessage
WScript.StdOut.WriteLine ""
End Sub
Now let's say I want to write in one script to a few log files but want to keep it constant.
We will change our SUB line to request another parameter from the WriteToLog line in the script
Sub WriteToLog(strLogMessage,strLogFileName)
As well another change to the log name in the function
strLogFileName = "C:\"& strLogFileName & ".log"
So what did we just do if our write to log like looks like this?
WriteToLog "Something for the VBScript Log","WhatAlog"
first area is our strLogMessage, second area is the log name strLogName
strLogMessage = "Something for the VBScript Log"
strLogName = "WhatAlog"
There are unlimited options here, have fun and ask away if you need.
Print This Post