- 1 What is the Windows Script Host (WSH)?
- 1.1 Common Editor for WSH Scripts
- 1.2 Below are the popular VBScript /VBS editors
- 1.3 From where to download WSH
- 1.4 How to Write Code for WSH or VBScript or VBS
- 1.5 How to Run WSH Scripts
- 1.6 What is the difference between CScript.Exe and WScript.Exe?
- 1.7 How to create a .WSH file?
- 1.8 Available Script Engines or Alternative of WSH
- 1.9 WSH Object Model
- 1.10 How to instantiate WSH Objects?
- 1.11 WSH Properties and Methods
- 1.11.1 Shortcut Properties
- 1.11.2 How to Create a shortcut?
- 1.11.3 How to delete a shortcut?
- 1.11.4 How to Modify a shortcut?
- 1.11.5 How to Change the Start menu or alter Start Menu?
- 1.11.6 How to add a shortcut to Quick Launch Toolbar?
- 1.11.7 How to access WSHUnnamed object?
- 1.11.8 How to use WSHNamed Object?
- 1.11.9 How to use item property?
- 1.11.10 Length
- 1.11.11 Count()
- 1.11.12 Exist()
- 1.11.13 Item Property
- 1.11.14 Length
- 1.11.15 Count() method
- 1.11.16 Remove() method
- 1.11.17 How to read the arguments from the Script?
- 1.12 Common tasks are done through WSH Script
- 1.13 Advantages of WSH Scripts
- 1.14 WSH Object Properties
- 1.15 WSH Object Methods
- 1.16 How to Work with WSHObject Properties?
- 1.17 How to Setup the Desktop Shortcuts of a website using VBScript?
- 1.18 Share and Enjoy !
|Windows Script Host (WSH)?|
What is the Windows Script Host (WSH)?
In this post, I will cover the windows script host (wsh) tutorial in step by step manner. By technology, it is a program that runs within the Windows environment and acts as a container to run VBScript files. It is a Windows administration tool. WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host.
It makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine. Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium Editions and higher versions.
A Windows script is a text file. We can create a script with any text editor as long as we save our script with a WSH-compatible script extension (.js, VBS, or .wsf).WSH also supports to write scripts in JScript, Perl, Python, REXX, other ActiveX scripting languages including VBScript.
Refer here for more details for WSH. I am highly encouraged by this site. This post is a lighter version of the same mostly applicable for UFT.
by writing a WSH script we can take advantage of ADSI and WMI. We will discuss these within a while.
List of Supporting technologies
|.bat||MSDOS batch file|
|.wsh||Windows Script host files|
|.wsf||Windows Script host files|
Common Editor for WSH Scripts
The most commonly available text editor is already installed on our computer ? Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++, or Visual InterDev.
Below are the popular VBScript /VBS editors
From where to download WSH
WSH can be downloaded from here.
How to Write Code for WSH or VBScript or VBS
Creating a script with Notepad
- Start Notepad.
- Write your script. For example purposes, type Msgbox “Hello VB Script”
- Save this text file with a .vbs extension (instead of the default .txt extension). For example, Hello.vbs
- Navigate to the file you just saved, and double-click it.
- Windows Script Host invokes the VB Script engine and runs your script. In the example, a message box is displayed with the message “Hello VB Script”
- Hosting Environments and Script Engines
Scripts are often embedded in Web pages, either in an HTML page (on the client-side) or in an ASP page (on the server-side).In the case of a script embedded in an HTML page, the engine component that interprets and runs the script code is loaded by the Web browser, such as Internet Explorer. In the case of a script embedded in an ASP page, the engine that interprets and runs the script code is built into Internet Information Services (IIS). Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files.
How to Run WSH Scripts
- Using command-line. It uses Cscript.exe. It is used in the MSDOS console window.
- Within Windows like double click on the script file. It uses WScript.exe. It is used in Windows GUI.
we can pass arguments to the Cscript as well:
If we run CScript.exe without any arguments , directly from the command line, we can get the usage notes.
The switches available to run a Cscripts are as follows:
|//B||Batch mode on Suppress the errors and prompts|
|//E:engine||Executes scripts by using the engine|
|//H:Cscript||Changes the host to Csript|
|//H: Wscript||Changes the host to Wscript|
|//I||Activates interactive mode|
|//Job:XXX||Executes a WSF job|
|//Logo||Activates and display a Logo|
|//NoLogo||Deactivate logo display|
|//S||Saves the command-line options for an active user|
|//T:nn||Sets time out in Seconds. A script can run ‘nn’ seconds. Post this time out the script just aborts|
|//X||Run the script in Debugger mode|
|//U||Activates Unicode for redirecting IO from the console|
Execute WSH using WScript.exe
Similarly, we can execute WSH scripts in the Windows environment using WScript.exe.
- The execution begins once we double click on the file. In this case, the file has to be registered with WSH.
- We can also use a Run command with the full path of the script and script name
However, if we run WScript from the command prompt, instead of getting output, we will get a configuration box for script customization options. If Ok is clicked after providing all customization options, It won’t run. It just saves the individual configurations for the script.
What is the difference between CScript.Exe and WScript.Exe?
The difference comes to existence when we debug a script. CScript.exe sends the error message directly to the console which is very convenient to use. Whereas WScript.exe shows the errors in the form of popup. So handling the huge number of popups would be tedious.
So while debugging we need to use CScript.exe and while running we need to use WScript.exe with Echo() method enabled.
How to create a .WSH file?
In order to create a .WSh file, we select a file that is currently associated with WScript(.js,.VBS,.wsf etc) then right-click on that.
Once the Properties dialog opens, navigate to different tabs. It will allow us to change the default configurations. We can make changes to them and can apply the changes. This will create a new .wsh file with the same script name.
It will be like below:
[ScriptFile] Path=D:\test\myTest.vbs [Options] Timeout=30 ... ...
Available Script Engines or Alternative of WSH
Generally, we write scripts in either Microsoft JScript or VBScript, the two script engines that ship with Microsoft Windows 98, 2000 and Millennium Editions.
We can use other script engines, such as Perl, REXX, and Python, with Windows Script Host.A stand-alone script written in JScript has the .js extension; a stand-alone script written in VBScript has the .vbs extension.
These extensions are registered with Windows. When we run one of these types of files, Windows starts Windows Script Host, which invokes the associated script engine to interpret and run the file.
WSH Object Model
WScript is the root of the object model. This object is automatically instantiated by WSH. It is called a public object. However, the WSH core object model provides three more public objects:
These three objects need to be created using a create object() method. All other objects in the WScript tree need to be explicitly instantiated to use their properties and methods.
All other objects also need to be created with the help of these four public objects.
WSH object model helps us to get the following information:
- Name and path information for the script it is executing.
- Version of WSH
- It helps to link to external objects
- It provides the ability to interact with the user.
- it provides ability to delay or terminate a script.
How to instantiate WSH Objects?
|Object||Ways to instantiate|
WSH Properties and Methods
|WshShell||Provides access to native Windows Shell, registry, event log, environment variables, shortcuts, and applications.|
WshShell Object has three properties:
WshShell Object provides eleven methods:
|WshShortcut||Provides methods and properties to coders to create and modify windows shortcut. A shortcut is like a link that connects another window resource.|
The difference between an application and a shortcut is that the shortcut has a small curved black arrow at the lower-left corner( indicating that this is the shortcut of the application.)
WshShortcut Object provides nine properties:
WshShortcut provides one method:
Since shortcut is a secondary object, I order to use shortcut object, we need to create an object of the primary a parent object.
Secondly, we need to establish a relationship with the location where we want to save the shortcut.
How to Create a shortcut?
Set WHSShell=Wscript.CreateObject("Wscript.Shell") MyDesktopFolder=WHSShell.SpecialFolders("Desktop") Set myNotepadShortcut=WSHShell.CreateShortcut(MyDesktopFolder & "\\Notepad") myNotepadShortcut.TargetPath="%windir%"\Notepad.exe" myNotepadShortcut.Save()
How to delete a shortcut?
WSHShortcut object provides Delete() method that can be used to delete a shortcut.
Set WHSShell=Wscript.CreateObject("Wscript.Shell") MyDesktopFolder=WHSShell.SpecialFolders("Desktop") Set myFSOObject=CreateObject("Scripting.FileSystemObject") Set myNotepadShortcut=myFSOObject.GetFile(MyDesktopFolder&\\Notepad) myNotepadShortcut.Delete()
How to Modify a shortcut?
Option Explicit Dim WHSShell,MyDesktopFolder,myNotepadShortcut Set WHSShell=Wscript.CreateObject("Wscript.Shell") MyDesktopFolder=WHSShell.SpecialFolders("Desktop") Set myFSOObject=CreateObject("Scripting.FileSystemObject") Set myNotepadShortcut=WSHShell.CreateShortcut(MyDesktopFolder & "\\Notepad") myNotepadShortcut.TargetPath="%windir%"\Notepad.exe" myNotepadShortcut.Description="My Reporting" myNotepadShortcut.Arguments="C:\MyReporting.log" myNotepadShortcut.Hotkey="ALT+CTRL+N" myNotepadShortcut.Save()
Set WHSShell=Wscript.CreateObject("Wscript.Shell") MyStartFolder=WHSShell.SpecialFolders("StartMenu") Set MyWindowShortcut=WHSShell.CreateShortcut(MyStartFolder& "\\word") MyWindowShortcut.TargetPath="C:\Program File\Microsoft Office\Office\Winword.exe" MyWindowShortcut.Save()
In the similar manner, we can create shortcuts for the notepad, WinZip, paint, adobe reader, FTP etc,
How to add a shortcut to Quick Launch Toolbar?
Set WHSShell=Wscript.CreateObject("Wscript.Shell") MyQuickLaunchToolBar=WSHShell.SpecialFolders("APPData") MyApplicationPath=MyQuickLaunchToolBar+"Microsoft\Internet Explorer\Quick Launch" MyQuickLaunchShortcut=WSHShell.CreateShortcut(MyApplicationPath+"\\Notepad") MyQuickLaunchShortcut.TargetPath="%windir%\notapad.exe" MyQuickLaunchShortcut.Save
In the similar manner, we can create shortcuts for the notepad, WinZip, paint, adobe reader, FTP etc,
|WshSpecialFolders||Provides access to the special folders that allow configuring start menu, desktop, a quick launch toolbar or other windows special folders.|
The special folders are:
WshSpecialFolders object provides two properties:
WshSpecialFolders object provides one method:
|WshUnnamed||Provides access to unnamed commands in Command line arguments. WshUnnamed object being a read-only collection, generally returned by Unnamed property of the WshArguments object. It uses a zero-based index to get the arguments.|
The ways to access command-line arguments:
WshUnnamed object provides two properties:
WshUnnamed object provides one method:
How to access WSHUnnamed object?
|WshUrlShortcut||It provides coders to create URL shortcuts from the Internet.|
WshUrlShortcut object provides two properties:
WshUrlShortcut object provides one method:
|WshScriptExec||Provides access to error information and status of the script which has been started using Exec() method.|
WshScriptExec has six properties:
WshScriptExec provides one method
|WshRemoteError||It provides error and status of the scrip when it terminates in the remote.|
WshRemoteError provides six properties:
WshRemoteError does not have any method.
|WshRemote||Provides access to remote scripts to perform administration on a remote computer over the network.|
WshRemote has two properties:
WshRemote has two methods:
|WshNetwork||It provides access to shared resources in the network like printers and drives.|
WshNetwork has three properties:
UserName has eight methods:
|WshNamed||It provides access to named commands in Command line arguments.|
WshNamed Object has two properties:
WshNamed Object has two methods:
The named property of WSHArguments object provides WSHNamed Object(a collection of arguments that have names). This collection retrieves individual argument values with the help of the index.
Below are the ways to access the command line arguments
How to use WSHNamed Object?
How to use item property?
The item property of the WSHNamed object provides access to the items.
Where the object is WSHNamed Object and key is the String name of the item that we want to fetch.
Item property of the WSHNamed object returns a String.
The length property of the WSHNamed object is a read-only integer that is used when we write JScript.
The count() method returns the total number of switches in the WSHNamed or WSHUnnamed objects.
Where object is Argument object.
For y=0 to WScript.Arguments.count-1 msgbox Wscript.Arguments.Named(y) Next
Exist() method returns a boolean value to indicate if the specific key value exists in the WSHNamed object.
Where the object is the WSHNamed object and key is the string value that represents an argument of the WSHNamed object. If the key exists in the WShNamed object it returns true, otherwise, it returns false.
|WshEnvironment||It provides access to a set of Microsoft Windows system environment variables.WshEnvironment is a collection of environment variables. These variables are returned by WSHshell object’s environment property. The collection contains the entire set of environment variables(named and without names). The retrieval of collection is via index value.|
WshEnvironment has two properties:
WshEnvironment provides two methods:
Dim WshShell Set WshShell=WScript.CreateObject("WScript.Shell") Set myEnv=WshShell.Environment("SYSTEM") msgbox myEnv("NUMBER_OF_PROCESS")
Item property exposes a specified item from a collection.
Where the object is the resultant of the EnumNetworkDrive or EnumPrinterConnection method or the object returned by the Environment or SpecialFolders property.
iIndex is the index to specify which item to fetch. For EnumNetworkDrive or EnumPrinterConnection collection index is an integer; for Environment or SpecialFolders index is a String.
The length property can be used in JScript.
The count() method returns a long value which says the number of items in the collection. Example count() method of NamedArgument.
Where object is the argument object.
Remove() method removes an existing environment variable.
Where object is WSHEnvironment object and sName is the String value that signifies the name of the environment variable that we want to remove.
The Remove() method can remove environment variables from the following types of environment
|WshController||Provides access to CreateScript() method in the remote script process.|
WshController provides one method called CreateScript() but does not provide any property.
|WshArguments||It provides access to the command line arguments/parameters. So WSHArguments objects are the way how to pass input to the script.|
WshArguments has four properties:
WshArguments provides two methods:
The WSHAgrument is a collection of objects returned by the WScript object’s Argument property.
There are three ways to access the command line arguments. They are as follows:
Example-The below example works on CScript.exe and WScript.exe
Set myArgs=WScript.Arguments for i=0 to myArgs.count-1 WScript.Echo myArgs.Item(i) Next
How to Pass Arguments to the VBScript?
Instead of hardcoding the test data into the script, we can dynamically pass the data via arguments to the script. We can configure the system in such a way that if we pass blank data as argument it will take data from the script itself or use some default values or may quite depending upon our settings.
Syntax to pass arguments
WScript xyz.vbs abc,xyz
How to read the arguments from the Script?
With the below-written code, we can read the arguments from the script.
Dim WSHArgs Set WSHArgs=WScript.Arguments msgbox "count of argument" & WSHArgs.Count For i=0 to WSHArgs.Count-1 msgbox WSHArgs.Item(i) Next
WSH provides an option to include two or more scripts(even though two scripts are written in two different languages) via Windows Script File(extension .wsf).
|WScript||Provides access to the WSH module for different methods, objects, and properties.|
WScript helps codes by providing the following:
WScript has the below properties:
WScript has the below methods:
|Scripting.Signer||Provides digital signature for a file for trust and authenticity.|
Scripting. Signer provides four methods. They are:
Common tasks are done through WSH Script
- Common repetitive network-related tasks
- Common repetitive admin related tasks like server and distributed computer management.
- User data manipulation.
- Create a standard application folder with the word, Excel, powerpoint, Winzip, adobe acrobat, paint, snipping tool, etc.
- Customize the quick launch toolbar with links.
- Customize the start menu.
- Scheduling disk cleanup and disk defragment utility
- Setup the printer network connection to the network printer pool.
- File share between computers and setup mappings drives to the common file servers.
- Add local administrative maintenance.
- UFT/QTP helper file
- Quick Prototype builder
- Desktop configuration-like add shortcut URL for company websites
- Setup each user’s screen saver to start after a certain period.
- Setup the screen saver images.
- Setup computer/desktop background image.
Advantages of WSH Scripts
- Quick – it is very fast to execute. The edit debug life cycle is shorter than compiled languages.
- A lot of platforms (mainly Windows)support VbScript
- It can be incorporated into other program written in other languages
- Very easy to learn and implement.
- No complicated IDE is required.
WSH Object Properties
|Length||returns the count of the enumerated items|
|Line||returns the line number for the current line in the input stream or provides|
the line number where an error occurred.
|Name||returns the name of Wscript object as String|
|Number||returns the access or pointer to an error number.|
|Arguments||Creates a pointer to the WSHArgument collection.|
|AtEndOfLine||Returns True if the end of line marker reached the end of the line in a stream, False otherwise.|
|AtEndOfStream||Returns True if control reached the end of the stream, False otherwise.|
|Character||Identifies the specific character in a line of code where an error occurred.|
|Column||Returns the current column position in the input stream.|
|ComputerName||Returns the computer name.|
|CurrentDirectory||Returns or sets a scripts current directory|
|Description||Returns the description for a specific shortcut.|
|Environment||Returns a pointer, referencing to WSHEnvironment.|
|Error||Returns a WSHRemoteError object|
|ExitCode||Returns the exit code from the script which started using Exec() method.|
|FullName||Returns a shortcut or executable program’s path along with the name.|
|Hotkey||Returns the hotkey for a shortcut.|
The modifier keys are:
1. CTRL- control key
The key combination can be-
|IconLocation||Returns the path of the Icon location|
|Interactive||Sets the scripts mode programmatically|
|Item||Returns the specified item from a collection or provide access|
to items stored in the WSHNamed object.
|Path||Returns the path of the folder from where the CScript or WScript execution starts.|
|ProcessID||Returns the PID(process identifier) for a process started using the WSHScripotExec object|
|ScriptFullName||Returns the currently executing script’s full path along with the name|
|ScriptName||Returns the name of the currently executing script.|
|Source||Returns the object that caused an error.|
|SourceText||Returns the source code that created an error.|
|SpecialFolder||Returns access to the windows special folder like-Start Menu.|
|Status||Returns the status information about a remote script that starts with Exec() command|
|StdErr||Returns access to write to the error output stream or provide access to read-only error output that is started with Exec()|
command. It returns an object that represents the standard error stream. This object can be accessed using cscript.exe only. If we use WScript.exe it will throw an error.
|StdIn||Returns access to a write-only output stream or provide access to the input stream that is started with Exec()|
command. It returns an object that represents the standard error stream. This object can be accessed using cscript.exe only. If we use WScript.exe it will throw an error.
|StdOut||Returns write access to the output stream or provide access to the write-only output stream that is started with Exec() command. It returns an object that represents the standard error stream. This object can be accessed using cscript.exe only. If we use WScript.exe it will throw an error.|
|TargetPath||Returns a shortcut path to the associated object.|
|UserDomain||Returns the domain name.|
|UserName||Returns the currently logged in UserName.|
|Version||Returns the WSH current version.|
|WindowsStyle||Returns a shortcut’s windows style.|
The windows Styles are:
1. Displays a window by restoring it to its location and size
2. Displays maximized windows
7. Minimizes the window
|WorkingDirectory||Returns the working directory of the specified Shortcut.|
WSH Object Methods
|AddPrinterConnection()||Maps a printer and creates the link.|
|AddWindowsPrinterConnection()||Creates a new windows environment printer connection|
|AppActivate()||Activates an application in windows.|
|Close()||Terminates and ends an already opened data stream.|
|ConnectObject()||Creates a connection to an object.|
|Count()||Returns the number of arguments found in the WSHNamed and WSHUnnamed object.|
|CreateObject()||Creates a new instance of the object and returns the instance.|
|CreateScript()||It creates a new instance of the WSHRemote object when Scripts is running remotely.|
|CreateShorcut()||Creates a new window shortcut.|
|DisconnectObject()||Disconnects from an object or terminates the connection.|
|Echo()||Displays a message in the form of Text.|
|EnumNetworkDrives()||Provides access to Network drives.|
|EnumPrinterConnection()||It provides access to network printers.|
|Exec()||Starts execution of a script in a child command shell and provides|
access to the environment variables.
|Execute()||Starts execution of a remote script as an object.|
|Exists()||Checks if a key exists in the WSHNamed object.|
|ExpandEnviromentSettings()||Returns the content of the process environment variables.|
|GetObject()||Returns the object.|
|RetResource()||Returns the resource’s value in the <resource> tag.|
|LogEvent()||Writes a log to the Windows Event log.|
|MapNetworkDrive()||Creates a mapping to the network drive.|
|Popup()||It creates a popup box and displays it.|
|Quit()||Terminates and ends scripts’s execution.|
|Read()||Returns a String character from the input stream.|
|ReadAll()||Returns the whole string from the input stream.|
|ReadLine()||Returns a line from the input stream as a String.|
|RegDelete()||Delete a registry key or value.|
|RegRead()||Returns a registry key or value.|
|RegWrite()||Creates a new registry key or values.|
|Remove()||Removes a specified environment variable.|
|RemoveNetworkDrive()||Removes a connection from the specified network drive.|
|RemovePrinterConnection()||Removes an active connection from a specified network printer.|
|Run()||It starts a new process in windows.|
|Save()||Saves the shortcut.|
|SendKeys()||Simulate a keystroke and type data.|
|SetDefaultPrinter()||Creates a default windows printer.|
|ShowUsage()||Returns information regarding the way that script is supposed to be executed.|
|Skip()||Skips n number of characters when reading an input stream.|
|SkipLine()||Skips a whole line while reading an input stream.|
|Sleep()||Stops script execution for the specified seconds.|
|Terminate()||Stops a process that is started with Exec() command.|
|Write()||Writes a String in the output stream.|
|WriteBlankLines()||Writes a blank line in the output stream.|
|WriteLine()||Write a line in the output stream.|
How to Work with WSHObject Properties?
Option Explicit Dim WSHNetwork Set WSHNetwork=Wscript.CreateObject("WScript.Network") msgbox "The computer is"& WSHNetwork.ComputerName & " and logged in user is"& WSHNetwork.UserName Set WSHNetwork=Nothing
How to Setup the Desktop Shortcuts of a website using VBScript?
Set WSHShell=Wscript.CreateObject("WScript.shell") myDesktopFolder=WSHShell.specialFolder("Desktop") Set myURLShortCut=WSHShell.CreateShortcut(myDesktopFolder+"\\Tech Travel hub homePage.url") myURLShortCut.TargetPath="http://techtravelhub.com/" myURLShortCut.save
This will create a Tech Travel hub home page shortcut on the desktop.
How to customize the Desktop wallpaper and Screensaver using VBScript or UFT?
Desktop wallpaper and Screensaver values are located at the HKCU\Control Panel\Desktop key. We need to work with them in order to make any alternation.
Option Explicit Dim WSHShell,changeSettings,shellApp,myFSOObject Set WSHShell=WScript.CreateObject("Wscript.Shell") Set myFSOObject=CreateObject(Scripting.FileSystemObject)
How to use WSH built-in Streams?
Dim streamOut, streamIn, streamErr Set streamOut = WScript.StdOut Set streamIn = WScript.StdIn Set streamErr = WScript.StdErr Dim strExt, strLineIn Dim intMatch strExt = WScript.Arguments(0) intMatch = 0 Do While Not streamIn.AtEndOfStream strLineIn = streamIn.ReadLine If 0 = StrComp(strExt, Right(strLineIn, Len(strExt)), _ vbTextCompare) Then streamOut.WriteLine strLineIn intMatch = intMatch + 1 End If Loop If 0 = intMatch Then streamErr.WriteLine "No files of type " & strExt & "found" else streamErr.WriteLine intMatch &" files of type " & strExt & "found" End If
We can run the above script by the following command and redirect the output to another text file.
cscript myFilter.vbs vbs >> logvbsfiles.txt
How to get a version of the WSH?
For this, we need to use WSH’s version property.
|A Message Box That Closes Automatically|
A Message Box That Closes Automatically in Vbscripting:
This is a very interesting criterion of an Automation Test Engineers to create a message box that will create itself—-> display—->and close automatically.
well, I have used this in some of the projects, Simple… the code is given below…
Set WshShell = CreateObject("Wscript.Shell") WshShell.Popup "Wait 5 seconds", 5, "Title" //need more clarifications.. //use this code.. set a = createobject("wscript.shell") msg="Messagebox will close automatically"'//Message you want to display time="5" title="testing" a.popup msg,time,title
but practically speaking it is of no use. If you want to display a message, we will not let it go. And in between a test, such a message will slow down the testing process. This can be treated as a programming process.