Install a Network Printer with VBScript

It’s worth noting that Windows Server 2012 R2 includes an easy way to install printers using Group Policy without the need to write a script, however this of us who love scripting prefer to do it ourselves. Scripting common system administrator tasks will empower you to apply logic not readily possible with a GPO (although WMI filtering can come close).

Here’s the script:

'Connect to a shared printer | Provided by http://vbscript.us
Set zNetwork = CreateObject("WScript.Network")    
zNetwork.AddWindowsPrinterConnection "\\Server\PrinterName"

First we are loading the WScript.Network module as a variable named, “zNetwork”.

Set zNetwork = CreateObject("WScript.Network")    

Next we are installing the printer. Assuming that your computer already has the driver for the printer built-in, or assuming that your print server is properly configured with drivers suitable for your computer, this should work fine. If either of the preceding statements are not true, this will probably not work for you and you will need to prepare by either pre-installing the driver, or by advertising the driver from your Print Server.

zNetwork.AddWindowsPrinterConnection "\\Server\PrinterName"

Thats the gist of it. If you followed along, you now know how to install a shared printer from a VBScript script file.

Have fun and keep scripting!

-Z.

Mapping a Network Drive with VBScript

So, you’re ready to graduate beyond mapping drives with “net use” via batch scripts eh? Then you have come to the right place.

Let’s dive in with out full script. As usual, I’ll ask that you read the script line by line and try to understand as much as you can before moving forward to the explanations.

Map a drive with VBScript | Provided by http://vbscript.us
Set zNetwork = WScript.CreateObject("WScript.Network")
zSharepath = "\\server\share" 
zNetwork.MapNetworkDrive "S:", zSharepath, False

There are a few things happening here. Lets pick them apart:

1) We load the module needed to connect to a server across the network. That module is called, “WScript.Network”, which we are assigning to the variable “zNetwork”.

Set zNetwork = WScript.CreateObject("WScript.Network")

2) We define the path to our share. Of course you will change the values shown to reflect the name (or IP address) of your server and the share name. Note that our script here assumes that the user account the script is running under already has permissions to access the shared directory. Although we could put a username and password in our file, as a CISSP candidate I can’t in good conscience contribute to such a horrible breach of security so I won’t cover how to put a username and password into a script in this tutorial.

zSharepath = "\\server\share" 

3) We perform tha actual mapping of the drive using the aptly named “MapNetworkDrive” method of the Script.Network module. We pass it the drive letter “S:”, and the path to the share, which is stored in the variable “zSharepath”. We also pass it the boolean value “False” to make sure the mapping is not reconnected in future user sessions. Of course if you want the drive to connect every time the user logs in you can change this to “True”.

zNetwork.MapNetworkDrive "S:", zSharepath, False

And there you have it. All you need in order to map drives with VBScript. Have fun and keep scripting!

-Z

Writing to a Text File with VBScript

In this tutorial we are going to write to a text file using only VBScript. This is a common operation for a scripting system administrator. Assuming that you are automating tasks that mere mortals (sysadmins doing things by hand) struggle through it’s probably a good idea if you keep log files for important operations, letting you know if they ran successfully or not. In our example we are going to write to a log file located at the root of our “C” drive.

You can, of course, place your output file anywhere on the system that the user or service running your script has permission to write to. Note that this script will overwrite an existing file if it exists and will create the file if it does not exist – again assuming that the script runner has permissions to the path you specify.

Here is the script. Read it and try to understand as much of it as you can before proceeding:

Set FSO=CreateObject("Scripting.FileSystemObject")
logFile="C:\tracking.log"
Set objFile = FSO.CreateTextFile(logFile,True)
objFile.Write "I have done something amazing!!!"
objFile.Close

We’re doing a number of things here, so lets take them one by one:

First we load the VBScript object we need to use as a variable called “FSO”:

Set FSO=CreateObject("Scripting.FileSystemObject")

Next we will tell our script what file we want to write to. This gets assigned to a variable called “logFile”:

logFile="C:\tracking.log"

Then we want to create the file. Don’t worry about the file already existing. If the file exists already, no other processes have the file open, and you have rights to the file, this will overwrite it anew:

Set objFile = FSO.CreateTextFile(logFile,True)

Now we will write our text to the file using the “Write” function of our FileSystemObject object:

objFile.Write "I have done something amazing!!!"

Finally we need to close the file so that other users and processes can read it or write to it:

objFile.Close

And that’s pretty much it. Assuming that you followed along you now have all the skills required to write text to files with VBScript.

Have fun and keep scripting!

-Z.

Read Text from a File with VBScript

In this tutorial we are going to master reading text from a text file. For ease of use I’ve opted not to read the file line by line, as most tutorials for this operation do. Being a longtime user of VBScript to solve real-world system administration and user interface challenges I have rarely run across a reason to read a text file line by line (excepting extremely huge files), and lots of reasons not to.

In many instances in the real world you will be reading files which reside on a remote server across a LAN, or even WAN, link. It’s generally a waste of bandwidth to keep reaching back across the network into a file for each line in a file, and can negatively impact system resources of both your system, and the remote system.

So first-off lets look at the entire script:

'Read from a text file with VBScript | Provided by http://vbscript.us
set filetext = CreateObject("Scripting.FileSystemObject").OpenTextFile("file.txt",1)
file = filetext.ReadAll
wscript.echo file
filetext.Close()
set filetext = Nothing

Please review the script above and try your best to understand what it does before proceeding. Make a mental note of the parts you don’t understand so the answers below will be better retained when you read them.

Here we go:

Step 1) We need to flag the the file path, the way we intend to interact with it, and to assign it to a variable. We will do this with the “Scripting.FileSystemObject” object. This object is built into VBScript out of the box.

set filetext = CreateObject("Scripting.FileSystemObject").OpenTextFile("file.txt",1)

The above script segment will create the VBScript object we need and then will immediately use it to open the text file we want. You may have noted that we are not using a real path in this example. This works because I’ve already created a file called “file.txt” (and have put some text into it for my script to read) in the same directory as my script file. You should do the same for this tutorial. Of course, if you want to put a full path to a text file in there you can, in which case instead of “file.txt” you’d enter something like, “c:\users\me\documents\file.txt”.

In the above script segment we also used a “1” parameter after our filename. That “1” means we want to open the file for reading (as opposed to writing).

Step 2) Next we need to actually load the contents of the file into memory. Be very careful with using this method for very large files as large files may eat up more of your RAM than your system can handle while remaining stable. For very large files you will want to read the contents line by line, which is beyond the scope of their particular tutorial.

We will load the contents of the file into memory like so:

file = filetext.ReadAll

This puts the entire contents of the file into RAM.

Step 3) Next we will tell Windows what to do with this text.

wscript.echo file

“Wscript.echo”, as you may know by now, outputs text to your console (usually a CMD or PowerShell window).

Step 4) Now that we’ve done what we want to do with our file and text, we need to cleanup so that the file is available for other users and services to read, and so that we don’t leave a large chunk of data in RAM that will slow down our system.

We close the file with:

filetext.Close()

And we cleanup our RAM usage with:

set filetext = Nothing
file = nothing

And there you go. You can now read text files with VBScript! Have fun and keep scripting!

-Z

Display a Future Date with VBScript

A common feature of many application and scripts is to return a date a certain number of days, weeks, or months in the future. Fortunately for us Microsoft has included in VBScript an awesome function called “DateAdd”.

DateAdd gives you several options, but for the purposes of this tutorial we’ll focus on the Day, Week, Month, and Year intervals.

To retrieve a date 7 days in the future we would use:

DateAdd("d",7,Date())

To retrieve a date 7 weeks in the future we use:

DateAdd("ww",7,Date())

To retrieve a date 7 months in the future we use:

DateAdd("m",7,Date())

To retrieve a date 7 years in the future we use:

DateAdd("yyyy",7,Date())

Of course if we want to save this as a variable we can use something like:

sevenyearshence = DateAdd("yyyy",7,Date())

And to pop this up in a small window we can use:

sevenyearshence = DateAdd("yyyy",7,Date())
MsgBox(sevenyearshence)

Displaying the Current Time with VBScript

From time to time you may have a reason to retrieve, reference, or display the current time as part of your VBScript script.

Here are some easy ways to get the current time. Just make sure you are aware that this is 100% dependent on the clock settings on your PC or server, so if they are wrong, your script will return the wrong time.

To get the time as a variable (for use later) you can simply use:

currTime = Time()

To display the time directly within your console output you can use:

wscript.echo Time()

To display the time in a popup window you could use:

MsgBox Time()

Launch any Application with VBScript

The developers over at Microsoft are, it’s safe to say, pretty smart on average and one measure of intelligence is understanding that you cannot possibly prepare for everything.

Fortunately for us the guys at Microsoft who developed VBScript definitely understood this and they had the foresight to give us a way to execute third party applications from within a VBScript script file.

Today you’ll learn how to do this from within your own scripts.

Lets assume that, for some reason, you want your application to open Notepad. I’m using Notepad because it’s included in every release of Windows that has a built-in web browser capable of accessing this website, so I feel comfortable in assuming that everyone who reads this tutorial will be able to follow along without having to substitute a different application.

'Launch an Executable | Provided by http://vbscript.us
Set zShell = WScript.CreateObject("WScript.Shell")
zShell.Run ("%windir%\notepad.exe")

This is pretty self-explanatory. We are loading the “WScript.Shell” VBScript object which allows us to work with the operating system, and then we are running the application “Notepad.exe” which is located in the Windows directory. The CMD variable “%windir%” always points to the directory Windows is installed in.

We are using the built-in function “Run”, which is a subset of the “Wscript.Shell” object. This function tells Windows to launch the referenced executable. You could, as you may imagine, use this to launch everything from a web browser, to your Bitcoin wallet, to a system shutdown command – although shutting down a computer or a server from an automated script is a very risk proposition. In my day-job doing application and server hosting on servers geographically separate from my office, the idea of an automated script having the power to shut down a production server would make me REALLY concerned.

Back to the subject at hand:

You may be thinking that it would be easier to just use “c:\windows\notepad.exe” instead, and you’d be right – for 95%+ of Windows computers and servers. However for that remaining percentage, in which cases a sysadmin may have (for one valid reason or another) loaded Windows onto a drive other than “C”, your script would utterly fail.

For this reason it’s advisable to use “%windir%” which always points to wherever the installation of Windows within which your script is being run is installed.

And thats how we run an executable from within a VBScript script file. There are tons of applications for this, but I’ll leave you to ponder what they may be and how you can use them to build something awesome.

Have fun and keep scripting!

-Z.

Scrape a List of Links from a Website with VBScript

This tutorial is a bit more advanced than some others, so I strongly suggest that you tackle a few other posts here before attempting this one as it will rely on several concepts we’ve covered in some of the simpler articles.

For this script we are going to use an Internet Explorer object. Essentially we are remote-controlling a hidden Internet Explorer window from within our script using the built-in “InternetExplorer.Application” object, which is a favorite object of mine in both VBScript and PowerShell.

Usually I prefer to unfold the parts of a script line by line but this one is best digested by first seeing the whole thing. Please read this line by line and try to determine what each line is doing.

'Scrape websites with VBScript | Provided by http://vbscript.us
path = "http://powershell.ws"

With CreateObject("InternetExplorer.Application")
	.navigate path
	Do until .readystate = 4
		Wscript.sleep 10
	loop

	for each link in .document.links
		wscript.echo link.innertext," : ",link
	next
End With

Now, lets pick it apart together.

First we define the path we want Internet Explorer to take. We need to navigate to a specific page to scrape links, of course.

We define that path with:

path = "http://powershell.ws"

Next we create the Internet Explorer object. Although we could create this object on its own line, and we would do so if we wanted to use the object in several subsequent operations, in this case it’s easiest to create and use it in one pass:

With CreateObject("InternetExplorer.Application")
	'Put some code here
End With

Now that we’ve got out object created we need to give it some commands. The first command is to navigate to the path we defined earlier. We can do so with this:

.navigate path

Unfortunately we aren’t yet in a world where websites load instantaneously. Because this is the case we have to tell our hidden browser to wait until the page loads before processing the rest of our code. Internet Explorer provides page load status as a value called “ReadyState”. We want a ReadyState of “4”, which means that the page is fully loaded and is ready for additional action or reading.

Do until .readystate = 4
	Wscript.sleep 10
loop

The above tells our hidden window to “sleep” until the page is fully loaded, indicated by a ReadyState of “4”. Sleep is, in many scripting and programming languages, the same thing as saying “Wait”.

Once the page is fully loaded our script will move past the section above and will process whatever comes after. in this case, we want to grab all the links from the page we now have loaded. We can do this with:

for each link in .document.links
	wscript.echo link.innertext," : ",link
next

This bears a bit of explanation. First we are defining a “For Each” loop. We are telling our scripthat for every link found in the document we should execute the code inside of the loop. That code is, of course:

wscript.echo link.innertext," : ",link

“Link” gives us the URL the link points to while “link.innerText” gives us the link’s label, which is the text shown to a human viewer of the page.

And there it is. If you followed along thus far, you know now how to scrape links from a web page using VBScript.

Have fun and keep scripting

-Z.

Replacing Text with VBScript

Lets say that we have a string assigned to a variable and we want to change a single word to a different one.

First we need a string:

txtblock = "Jeremiah walked to the store.  While on the way to the store he happened to notice an old man humming a familiar tune.  Intrigued, Jeremiah asked the old man what the name of the song he was humming was.  The old man paused and considered Jeremiah with a cold stare.  After what seemed like an eternity the old man said, 'You are both the song and the listener'.  Jeremiah was understandably confused."

Ok. We have our string. Now lets pick a word to replace. The easiest one in our string is the protagonist, “Jeremiah”. So lets assign “Jeremiah” as the value of another variable:

oldstring = "Jeremiah"

Now that we’ve got an old value to replace, we need a new value to replace it with. We’ll use, in this case, “William”:

newstring = "William"

Now, we just need to employ a handy function called “Replace”.

newblock = Replace(txtblock,oldstring,newstring) 

And that’s pretty much all there is to it. Have fun and keep scripting!

List the Days of the Week with VBScript

For various reasons you might one or more days of the week in your script. Of course you could hand-type them but, we scripters never want to hand-key unless we have a really good reason to do so. Therefore:

VBScript has a function called WeekDayName which when fed a numeral between one and seven, will return the corresponding weekday name. For example:

WeekDayName(1)

The above function call will give you “Monday” when executed.

You can probably figure out on your own now how to get the other weekday names, so I won’t bore you by putting them all here, however a helpful bit of code for you is:

for i = 1 to 7
	wscript.echo WeekdayName(i)
Next

The above script will output to your console each of the days of the week. Of course you can exchange “wscript.echo” for any other function you need to apply each day of the week to.

Have fun.

Displaying the Current Date with VBScript

Very often you will have a reason to retrieve, reference, or display the current date as part of your VBScript script.

Fortunately Microsoft has made this easy. VBScript includes a very helpful function called “Date” out of the box. To retrieve the date as a variable (for use later in your script) you can simply use:

currDate = Date()

Alternatively, if you want to display the date directly within your console output you can use:

wscript.echo Date()

And finally, if you want to display the date in a popup window you could use:

MsgBox Date()

Search for and Replace Text within a Text File

This script will search and replace text within a file. The first few lines are all you generally will need to change to customize the script to your needs.

‘This will replace whatever you put as the “oldText” value with whatever you put as the “newText” value in the file you put as the “filePath” value. | Provided by http://vbscript.us

oldText = “Something Incorrect”
newText = “Something Correct“
filePath = "C:\Scripts\Text.txt"

Const ForReading = 1
Const ForWriting = 2

Set objFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystemObject.OpenTextFile(filePath, ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, oldText, newText)

Set objFile = objFileSystemObject.OpenTextFile(filePath, ForWriting)
objFile.WriteLine strNewText
objFile.Close

Play a sound file with VBScript

This script will play a sound file.  Any WAV File will do.

 

'Play a WAV file with VBScript | Provided by http://vbscript.us
Set oVoice = CreateObject("SAPI.SpVoice")
set oSpFileStream = CreateObject("SAPI.SpFileStream")
oSpFileStream.Open "C:\Windows\Media\tada.wav"
oVoice.SpeakStream oSpFileStream
oSpFileStream.Close

Send Email with VBScript

This script will send an email using VBScript. To use this you will need access to an SMTP Server. If you don’t have your own, your internet service provider may provide one free of charge to you for use. Check your ISP’s help pages to see.

‘Send Email with VBScript | Provided by http://vbscript.us
strMailFrom = “noreply@somecompany.com"
strMailTo = “someone@someothercompany.com"
strMailRelay = "smtp relay server"
‘Either Name or IP Address will work on the line above
strBody = “Email message test“
strMySubject = “Subject Text”
strPathToAttachment = “c:\somefolder\somefile”


Set oMessage = CreateObject("CDO.Message")
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strMailRelay
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMessage.Configuration.Fields.Update
oMessage.Subject = strMySubject
oMessage.From = strMailFrom
oMessage.To = strMailTo
oMessage.TextBody = strBody
oMessage.AddAttachment strPathToAttachment
oMessage.Send

Create a Desktop Shortcut to a Shared Folder

This handy script will create a desktop shortcut to any path you specify.

For this example we have set it to a shared folder called “myshare” on a server called “myserver”. Be sure to change this path to whatever will work in your environment.

We also named the shortcut “FancyName”. you will probably want to change this to something more descriptive for you.

'Creates a desktop shortcut | Provided by http://vbscript.us
SET FIleSystemObject = Wscript.CreateObject("Scripting.FileSystemObject")
strCorePath = WshShell.SpecialFolders("Desktop")
' Set the shortcut label
strshortcut = strCorePath & “\FancyName.lnk"
If Not FIleSystemObject.FileExists(strshortcut) Then
SET oLinkVal = WshShell.CreateShortcut(strshortcut)
' Set the server share path to point to.
oLinkVal.TargetPath = “\\myserver\myshare\”
oLinkVal.Save
End If

Faster Downloads with Internet Explorer

This will increase the number of simultaneous downloads in Internet Explorer to twenty, instead of the lower amount Windows restricts you to by default.  As a result, as long as you have a fast connection to the web, downloads of multiple files should generally finish faster.

'Faster IE Downloads | From http://vbscript.us/
Dim IERegpath
IERegpath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\"
WSHShell.RegWrite IERegpath & "MaxConnectionsPer1_0Server","20","REG_DWORD"
WSHShell.RegWrite IERegpath & "MaxConnectionsPerServer","20","REG_DWORD"

	

Add a Send-To option to open the file in Notepad

This script will add an option to your Send-To menu (a subset of the “context menu”) to open the currently selected item(s) in Notepad.

'Adds an option to the Send-To menu for opening an item in Notepad | From http://vbscript.us/
SendFolder = WSHShell.SpecialFolders("SendTo")
NotePadPath = WinDir & "\system32\Notepad.exe"
Set obSHTCT = WSHShell.CreateShortcut(SendFolder & _
"\Notepad.lnk")
obSHTCT.TargetPath = NotePadPath
obSHTCT.Save

Add a Right-Click option to move any item to any other folder

This script will add an option to your right-click menu (often called the “context menu”) to move the currently selected item(s) to a folder of your choosing.

' Add a Move To option to your context menu | Provided by http://vbscript.us
'=====================================
On Error Resume Next
Dim copypath
copypath = "HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\"
WSHShell.RegWrite copypath,"MoveTo"
WSHShell.RegWrite copypath & "\MoveTo\","{C2FBB631-2971-11d1-A18C-00C04FD75D13}"

Add a Right-Click option to copy any item to any other folder

This script will add an option to your right-click menu (often called the “context menu”) to copy the currently selected item(s) to a folder of your choosing.

' Add a Copy To option to your context menu | From http://vbscript.us/
'=====================================
On Error Resume Next
Dim copypath
copypath = "HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\"
WSHShell.RegWrite copypath,"CopyTo"
WSHShell.RegWrite copypath & "\CopyTo\","{C2FBB630-2971-11D1-A18C-00C04FD75D13}"

Open a Command Prompt in the Current Folder

This script will add an option to your right-click menu (often called the “context menu”) to open a command prompt in the folder location you are currently browsing in Windows Explorer.

Every system admin who’s worked with Windows for awhile will have had an occasion when not having to manually “cd” your way to a folder just to run an executable or script with command line options would have been a huge time saver.

'This will open a command prompt at the current folder location you are browsing | From http://vbscript.us/
'=====================================
On Error Resume Next
Dim currpath, currpath2
currpath = "HKCR\Directory\shell\DosHere\"
WSHShell.RegWrite currpath,"Command &Prompt Here:","REG_SZ"
WSHShell.RegWrite currpath & "command\",WinDir & "\System32\cmd.exe /k cd "& Chr(34) & "%1" &Chr(34),"REG_SZ"

currpath2 = "HKCR\Drive\shell\DosHere"
WSHShell.RegWrite currpath2,"Command &Prompt:","REG_SZ"
WSHShell.RegWrite currpath2,"Command &Prompt Here","REG_SZ"
WSHShell.RegWrite currpath2 & "command\",WinDir & "\System32\cmd.exe /k cd "& Chr(34) & "%1" &Chr(34),"REG_SZ"
'=====================================

Rename “This Computer” Icon to the current computer name

Use this script to change the “This Computer” icon (which used to be “My Computer” in older Windows versions) to the current computer name.

 

'This will rename the "This Computer" icon with the current computer name | From http://vbscript.us/
ThisPCPath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
WSHShell.RegWrite ThisPCPath & "\", strComputer, "REG_SZ"

Delete Temporary Internet Files when Internet Explorer is Closed

This script will help keep you safer by deleting potentially malicious “sleeper code” when you close your browser. This will also help keep your disk space usage down by preventing all the images, scripts, and more you collect from the sites you visit from building up over time.

' This will delete your temporary internet files when you close Internet Explorer | From http://vbscript.us/
'=====================================
Dim tempdirectory
tempdirectory = "HKCU\Software\Microsoft\Windows\"

WSHShell.RegWrite tempdirectory & "ShellNoRoam\MUICache\@inetcplc.dll,-4750","Empty Temporary Internet Files folder when browser is closed","REG_SZ"

WSHShell.RegWrite tempdirectory & "CurrentVersion\Internet Settings\Cache\Persistent","0","REG_DWORD"
Set tempdirectory = nothing

 

Show Windows version on the desktop

Use this script if you want to show the Windows version on the desktop.  Note that this script must be run once per user to take effect.

'This shows the Windows version and service pack at the bottom-right of the desktop | from http://vbscript.us
'=====================================
HKEY_CURRENT_USER = &H80000001
strComputer = WSHNetwork.Computername
Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = "Control Panel\Desktop"
objReg.CreateKey HKEY_CURRENT_USER, strKeyPath
ValueName = "PaintDesktopVersion"
dwValue = 1
objReg.SetDWORDValue HKEY_CURRENT_USER, strKeyPath, ValueName, devalue
To deploy this to a single user:

http://vbscript.us/running-a-vbscript-at-logon-to-a-single-computer/