Vbscript
Vbscript
#vbscript
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Examples 4
1. Arrays - Static 4
2. Arrays - Dynamic 4
6. For Loop 5
8. Do While Loop 5
9. Do Until Loop 5
3. Arrays - Multi-Dimensional 5
Introduction 7
Parameters 7
Examples 7
Hello World 7
Explanation 7
Examples 9
Examples 11
Copying a File/Folder 12
Moving a File/Folder 12
Introduction 15
Remarks 15
Examples 15
Including files 16
Global initialization 16
Chapter 7: InputBox 17
Syntax 17
Parameters 17
Remarks 17
Examples 17
Chapter 8: Strings 18
Remarks 18
Examples 18
1. Standard String 18
3. Searching a String 19
5. Populating array with specific text from string via start and end characters. 20
Examples 21
Creating a Class 21
Introduction 23
Examples 23
Credits 25
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: vbscript
It is an unofficial and free vbscript ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official vbscript.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ 1
Chapter 1: Getting started with vbscript
Remarks
VBScript (VBS) is a Visual Basic-flavored scripting language for Internet Explorer and Windows. It
can be used on the web in principle, like JavaScript, but does not have much support, so it's
usually confined to standalone or server-side scripts in business environments that use Windows
exclusively.
Versions
1.0 1996-08-13
2.0 1996-12-14
3.0 1997-10-01
4.0 1998-06-01
5.0 1999-03-01
5.1 1999-12-01
5.5 2000-07-01
5.6 2001-08-27
5.7 2006-10-18
5.8 2009-03-19
Examples
Hello World message using cscript and wscript
This displays a message on the console if run with cscript.exe (the console host) or in a message
box if run with wscript.exe (the GUI host).
If you're using VBScript as the server-side scripting language for a web page (for classic ASP, for
example),
https://riptutorial.com/ 2
Response.Write "Hello world!"
puts the message into the HTML send to the client (browser).
If you want to displays a message in the message box, you can use:
https://riptutorial.com/ 3
Chapter 2: Arrays and Loops
Examples
1. Arrays - Static
Dim cars(2)
cars(0) = "Ford"
cars(1) = "Audi"
cars(2) = "Prius"
2. Arrays - Dynamic
Dim cars()
Redim cars(0) 'Give it 1 entry
Dim tmp
tmp = "Ford"
Dim cars
Dim filefullname : filefullname = "C:\testenv\test.txt"
'If you can, create an instaneous read for text file data for better memory handling.
'Unless it's a large file and that's impossible.
cars = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(filefullname, 1).ReadAll,
vbcrlf)
You cannot alter the array's contents through the loop variable because it's a temporary each
element is being assigned to.
https://riptutorial.com/ 4
Dim jeeps : jeeps = 0
For Each car in cars
If car = "Jeep" Then jeeps = jeeps +1
Next
6. For Loop
Dim i, cars(2)
cars(0) = "Ford"
cars(1) = "Audi"
cars(2) = "Prius"
For i=0 to ubound(cars)
If cars(i) = "Audi" Then Exit For
Next
8. Do While Loop
Dim x, cars
x = 0
cars = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\testenv\example.txt",
1).ReadAll, vbcrlf)
Do While x < ubound(cars)
If cars(x) = "Audi" Then Exit Loop
x = x + 1
Loop
9. Do Until Loop
3. Arrays - Multi-Dimensional
Dim mdArray(2,3)
mdArray(0, 0) = "test1"
mdArray(0, 1) = "test2"
mdArray(0, 2) = "test3"
mdArray(0, 3) = "test4"
mdArray(1, 0) = "test5"
mdArray(1, 1) = "test6"
mdArray(1, 2) = "test7"
mdArray(1, 3) = "test8"
https://riptutorial.com/ 5
mdArray(2, 0) = "test9"
mdArray(2, 1) = "test10"
mdArray(2, 2) = "test11"
mdArray(2, 3) = "test12"
Dim mddArray()
ReDim mddArray(0)
Dim ti, testinc: testinc = "test": ti = 1
For i = 0 To 4
Dim tmpArray(): ReDim tmpArray(0)
For j = 0 To 3
tmpArray(UBound(tmpArray)) = testinc & ti
ti = ti + 1
ReDim Preserve tmpArray(UBound(tmpArray) + 1)
Next
ReDim Preserve tmpArray(UBound(tmpArray) - 1)
mddArray(i) = tmpArray
ReDim Preserve mddArray(UBound(mddArray) + 1)
Next
ReDim Preserve mddArray(UBound(mddArray) - 1)
https://riptutorial.com/ 6
Chapter 3: Creating Your First Script
Introduction
To begin, in Windows, create a text document on your desktop (Right-click>New>Text Document.)
Change the the extension from ".txt" to ".vbs". At this point it is executable by double clicking
it(nothing will happen if you try, there's nothing in it yet.) To edit, right-click document and click
edit. Add the example code for your first program.
Parameters
Column Column
Cell Cell
Examples
Hello World
Just a simple hello world to start. Copy paste the below into the document, save then double click.
Explanation
https://riptutorial.com/ 7
"MsgBox" displays a message in a dialog box and waits for the user to respond.
This is a good method to inform users of actions to be performed or simply the end of the script.
Such as:
https://riptutorial.com/ 8
Chapter 4: Dictionary Objects
Examples
Create dictionary and Add Items to dictionary
Dim oDic
Set oDic = CreateObject("Scripting.Dictionary")
oDic.Add "US", "United States of America"
oDic.Add "UK", "United Kingdom"
If oDic.Exists("US") Then
msgbox "The Key US Exist. The value is " + oDic("US")
Else
msgbox "Key Does not exist."
End If
If oDic.Exists("UK") Then
oDic.remove("UK")
End If
*Output:
United Kingdom
Canada
https://riptutorial.com/ 9
oDic.add "USA", "United States of America"
oDic.add "UK", "United Kingdom"
oDic.add "CAN", "Canada"
https://riptutorial.com/ 10
Chapter 5: FileSystem Objects
Examples
Checking for the existence of a file/folder/drive
Methods used:
The following code checks for the existence of a file using the "FileExists" method of a file system
object. For checking the existence of Folder or a drive, one can use the method "FolderExists" or
"DriveExists" respectively.
Code:
Methods used:
The following example illustrates the Deletion and creation of a folder using the methods "
DeleteFolder" and "CreateFolder".
Code:
https://riptutorial.com/ 11
objFso.DeleteFolder strFolderPath, True 'True indicates forceful
deletion
End If
Copying a File/Folder
Methods Used:
The following code illustrates the use of CopyFile method to copy a file to a new location. The
same thing can be achieved for the folders by using the CopyFolder method.
Code:
Moving a File/Folder
Methods Used:
.MoveFile(Source, Dest)
.MoveFolder(Source, Dest)
The following code illustrates the use of MoveFile method to Move a file to a new location. The
same thing can be achieved for the folders by using the MoveFolder method.
Code:
https://riptutorial.com/ 12
Dim objFso, strSourcePath, strDestPath
strSourcePath = "C:\Users\GS\Desktop\Source.txt"
strDestPath = "C:\Users\GS\Desktop\Folder\Dest.txt"
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(strSourcePath) then
objFso.MoveFile strSourcePath, strDestPath
End If
Set objFso = Nothing
NOTE: We do not have any method of a filesystem object which allows us to rename a file.
However, this can be achieved by MoveFile method by moving the file to the same location with a
different name as shown below:
Methods used:
We can set an object reference to a folder using the getFolder method and perform different
operations on them.
Code:
Dim objChildFolders
Set objChildFolders = objFolder.SubFolders 'Returns the collection of all subfolder
Dim objChildFiles
Set objChildFiles = objFolder.Files 'Returns the collection of all files
contained in the folder
https://riptutorial.com/ 13
strDestPath and overwrite Flag=True
objFolder.Delete True 'Deletes the Folder; True indicates forceful
Deletion
objFolder.Move strDestPath 'Moves the Folder to the path contained in
strDestPath variable
objFolder.CreateTextFile strFileName, True 'Created a new text file inside the folder
and overwrites the existing file(if it exists)
Set objChildFiles = Nothing
Set objChildFolders = Nothing
Set objFolder = Nothing
Set objFso = Nothing
Methods Used:
We can set an object reference to a file using the getFile method and perform different operations
on them.
Code:
https://riptutorial.com/ 14
Chapter 6: Include files
Introduction
When running VbScript in Windows shell, there is no built in function to include a file, therefore, to
organize your code in different files you'll need to create a method to do that.
Remarks
A few things to keep in mind when using the IncludeFile(p_Path) method :
• There is no limitation of file type that can be included but the included files content must be
VbScript.
• If there is a syntax error in the included file, you will not get the line/column of the error.
• You must define and initialize std_internal_LibFiles before the first call to
IncludeFile(p_Path)
• You can use IncludeFile(p_Path) anywhere in your code, including other methods.
Examples
Creating an "include file" method
• Be standalone because it needs to be written in the main VbScript file and cannot be in an
included file (because it defines the include function)
• Provide enough information if something goes wrong (ie. the file that was being included, the
error that occurred, ...)
• Include a file once and only once to avoid include loops.
'
*************************************************************************************************
Sub IncludeFile(p_Path)
' only loads the file once
If std_internal_LibFiles.Exists(p_Path) Then
Exit Sub
End If
https://riptutorial.com/ 15
' opens the file for reading
On Error Resume Next
Set objFile = objFso.OpenTextFile(p_Path)
If Err.Number <> 0 Then
' saves the error before reseting it
strErrorMessage = Err.Description & " (" & Err.Source & " " & Err.Number & ")"
On Error Goto 0
Err.Raise -1, "ERR_OpenFile", "Cannot read '" & p_Path & "' : " & strErrorMessage
End If
Including files
IncludeFile "myOtherFile.vbs"
Global initialization
Dim std_internal_LibFiles
Set std_internal_LibFiles = CreateObject("Scripting.Dictionary")
https://riptutorial.com/ 16
Chapter 7: InputBox
Syntax
• InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
Parameters
Argument Detail
Text to display above the input field (usually an instruction as to what is required
prompt
form the user).
A placeholder for the text field, used as the return value if the user doesn't
default
overwrite.
xpos Horizontal distance in twips to display input box from the left edge of the screen.
ypos Vertical distance in twips to display input box from the top edge of the screen.
A string to determine the help file to be used in order to provide contextual help
helpfile
with the input box.
Remarks
1All arguments except prompt are optional.
2helpfile and context are coupled - if one is supplied, the other must also be supplied.
Examples
Use InputBox to assign user input to a string
' Omitting the 4th and 5th argument ("xpos" and "ypos") will result in the prompt
' being display center of the parent screen
exampleString = InputBox("What is your name?", "Name Check", "Jon Skeet", 2500, 2000)
https://riptutorial.com/ 17
Chapter 8: Strings
Remarks
MSDN Date/Time, String and Numeric Functions
https://msdn.microsoft.com/en-us/library/3ca8tfek(v=vs.84).aspx
Examples
1. Standard String
In vbscript, an object doesn't necessarily need a designated type. Similar to C#'s var variable.
'Base string
Dim exStr : exStr = " <Head>data</Head> "
'Left
Dim res: res = Left(exStr,6) 'res now equals " <Head"
'Right
Dim res: res = Right(exStr,6) 'res now equals "Head> "
'Mid
Dim res: res = Mid(exStr,8,4) 'res now equals "data"
'Replace
Dim res: res = Replace("variable", "var", "") 'res now equals "riable"
'LCase
Dim res: res = Lcase(exStr) 'res now equals " <head>data</head> "
'UCase
Dim res: res = UCase(exStr) 'res now equals " <HEAD>DATA</HEAD> "
'LTrim
Dim res: res = LTrim(exStr) 'res now equals "<Head>data</Head> " notice no space on left side
'RTrim
Dim res: res = RTrim(exStr) 'res now equals "<Head>data</Head> " notice no space on right side
'Trim
Dim res: res = Trim(exStr) 'res now equals "<Head>data</Head>"
'StrReverse
Dim res: res = StrReverse(exStr) 'res now equals " >daeH/<atad>daeH< "
'String
Dim res: res = String(4,"c") 'res now equals "cccc"
https://riptutorial.com/ 18
Dim res: res = StrComp("cars", "CARS") 'res now equals -1
Dim res: res = StrComp("cars", "cars") 'res now equals 0
Dim res: res = StrComp("CARS", "cars") 'res now equals 1
'Text
'-1 = if Text structure of "cars" < "CARSSS"
' 0 = if Text structure of "cars" = "cars"
' 1 = if Text structure of "CARSSS" > "cars"
Dim res: res = StrComp("cars", "CARSSS", 1) 'res now equals -1
Dim res: res = StrComp("cars", "cars", 1) 'res now equals 0
Dim res: res = StrComp("CARSSS", "cars", 1) 'res now equals 1
'Space
Dim res: res = "I" & Space(1) & "Enjoy" & Space(1) & "Waffles" 'res now equals "I Enjoy
Waffles"
3. Searching a String
Ford
Jeep
Honda
https://riptutorial.com/ 19
For car = 0 To ubound(cars)
If InStr(cars(car), searchstring) Then
position = car
Exit For
End If
Next
5. Populating array with specific text from string via start and end characters.
'Note: I use this method to extract non-html data in extracted GET telnet results
'This example effectively grabs every other vehicle that have start and finish
'characters, which in this case is "/".
'Resulting in an array like this:
'extractedData(0) = "/Jeep"
'extractedData(1) = "/Ford"
'extractedData(2) = "/Honda"
Dim combined : combined = Join(cars, "/") & "/" & Join(cars, "/")
'combined now equals Ford/Jeep/Honda/Ford/Jeep/Honda
Dim res
res = Ucase(Replace(Mid(exStr, instr(exStr, ">")+1,4), "ata", "ark"))
'res now equals DARK
'instr(exStr, ">") returns 7
'Mid(" <Head>data</Head> ", 7+1, 4) returns "data"
'Replace("data", "ata", "ark") returns "dark"
'Ucase("dark") returns "DARK"
https://riptutorial.com/ 20
Chapter 9: Using Classes
Examples
Creating a Class
Class Car
Private wheels_
Private distances_
' Method
Public Function GetTotalDistance()
dim d
'GetTotalDistance = 0
For Each d in distances_
GetTotalDistance = GetTotalDistance + d
Next
End Function
End Class
https://riptutorial.com/ 21
' Using a subroutine in a class
myCar.Drive 10
myCar.Drive 12
Class Car
...
' Parameterless Constructor
Public Sub Class_Initialize()
distances_ = Array(0)
End Sub
https://riptutorial.com/ 22
Chapter 10: WMI queries
Introduction
VBScript can query Windows Management Instrumentation (WMI) for various vital info related to
local and remote PC . We can use WMI queries to perform various tasks such as extracting PC's
name , getting screen resolution , getting info about user and username , extracting vital info about
any process , modifying core system settings,etc .
Below are some examples which use WMI queries to carry out specific tasks .
Examples
Extracting Local PC's name
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" &
strComputer & "\root\cimv2")
strComputer = "."
instances = 0
processName = "chrome.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_DesktopMonitor",,48)
https://riptutorial.com/ 23
WScript.Echo "ScreenHeight: " & objItem.ScreenHeight
WScript.Echo "ScreenWidth: " & objItem.ScreenWidth
Next
https://riptutorial.com/ 24
Credits
S.
Chapters Contributors
No
https://riptutorial.com/ 25