VB Script





VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.

Share tech news, updates, or what's on your mind.

Sign up to Post

Leaving sensitive information (like passwords) in clear text scripts is never a good practice, though it's sometimes unavoidable. This set of VBScript functions can be used to obscure critical information making it at least a little more difficult for curious eyes (or worse) to see.
LVL 100

Author Comment

by:Lee W, MVP
LVL 67

Expert Comment

Things that need elevation will not work that way unless UAC is off, or you use the built-in administrator, Lee, because for that account, UAC is off.  I wouldn't recommend to use it for this purpose for another reason: startup scripts or immediate tasks do the same much easier.
Announcing the Winners!
LVL 19
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script under elevated privileges/admin privileges
Decision Making
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.

Expert Comment

by:Brendan Wilson
This is an excellent article. I appreciate you taking the time to write this.

Expert Comment

by:Judy Deo
Thanks for taking the time to post this in such detail. Appreciate it.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.

Expert Comment

by:sudhir singh
if we want to run this script for a group of computer only not domain wide ?
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take you a long step deploying successfully.
LVL 68

Expert Comment

by:Jim Horn
Nice article, voted yes.   I think this article can be improved if the script were rendered in pieces-parts code blocks, with helpful text explanation on what the script does, so that experts can get an understanding and manipulate if they have to.
Not long ago I saw a question in the VB Script forum that I thought would not take much time. You can read that question (Question ID 28455246) Here. The asker wanted some help getting a script to update the custom.dic file for dictionary values in Microsoft Office. I thought no problem, it is just a text file. So I took a look at the code and it looked fine, but then I tried to run it and got the same error. I thought, well, that is strange, it is just a simple text file. Oh, but it is not.

When I opened it in Notepad++ I found that the encoding was not the standard utf-8, but rather it showed as UCS-2 Little Endian. I figured it cannot be that hard to write a script to update this file, so I took a whack at it. Needless to say after much searching in the internet and much more time than I had planned to spend on the question, I had nothing. That never feels good.

I took a break for the day and came back the next morning. Several ideas I found that should work did not. I had headed down the path of opening the file, saving it as UTF-8, and then opening it again and saving it back out. I found some scripts that could do that process, but all failed when I tried to add text. Eventually I stumbled across the right combination and sequence.
I decided since all the …
LVL 15

Administrative Comment

by:Eric AKA Netminder

Congratulations; your article has been published, and has received EE-Approved status as well.

Page Editor
This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over  the limited options we had scripting in Task Scheduler 1.0.  As I started my journey of knowledge I found some decent references for the objects on msdn, but could not find very many good sample scripts.  There were bits and pieces that told me how to do a few things, but a full picture was not readily available.  I decide to build my own full sample script so that I could reference it in the future.  I started by just building a script to return all the data from already scheduled tasks (see my article at http://rdsrc.us/vVxA6N for that script).  My next task was to build a script that could create all the options available for a new task.  I found that objects available actually presented more options for creating a task than one even has using the GUI.  These objects are pretty powerful and nice to use.  As a programmer, I found I had way more options than in task scheduler 1.0 and could do numerous items.  There were a couple objects that appear they are only available for the new C++ interface and therefore I have left those out.

Below is my script that will set up a task with all the different trigger options and all the different action options.  You can take this script and remove the pieces you don't need to create you own script to schedule your task.  I have put links to the msdn references in the comments of the …

Expert Comment

Dear ltlbearand3 ,

Thank you very much.
Over the years I have built up my own little library of code snippets that I refer to when programming or writing a script.  Many of these have come from the web or adaptations from snippets I find on the Web.  Periodically I add to them when I come across something I have not yet done.  Recently I needed to work with Task Scheduler 2.0 using VB Script.  I found that sample scripts were in short supply with most not having enough of the objects in them.  Luckily the Documentation is decent, but I still wanted a sample script.  Therefore I built a script for myself that would list all scheduled tasks and their properties.  I wanted to share for anyone else who was looking.

Task Scheduler 2.0 was originally released with the Vista operating system and should be the object used when looking at scheduled tasks in the newer Microsoft Operating Systems.  It will give you access to some of the many new options introduced in that version.  Since Task Scheduler 2.0 is not available on older operating systems, just be aware that this code will not work on those systems.

The script below will list all created tasks with their options and save it to a text file of “C:\TaskListing.txt.”  This file name and/or path can be updated at the beginning of the script (Line 7).    I have added a comment in each section with a link to the relevant documentation for that section.  The code has all the possible properties and conversions so that you can see all the options.  You should be able …

Expert Comment

First, EXCELLENT article/explanation. Your articles on Task Scheduler 2 are the only ones I've found. Any thoughts on what could be done to list tasks created by other local and/or domain accounts? The script works on my computer but does not show all tasks in the "root". Some tasks that aren't enumerated use a domain service account (which I don't have permission to).

Windows 7 SP 1, 32 bit.  I'm an administrator on the computer, administrator for computers in my OU (not full domain/forest administrator).

Experts Exchange owes you one because you're the only reason I've decided to get a paid account.
LVL 20

Author Comment

Polito T,

I am glad you found the article helpful and thanks for the kind words.  

Concerning your question, you would be best suited to handle this as a question in the VBscript forum.  That is monitored by some really smart people, who can also jump in to help out if the article author is not available.  I don't have an easy answer to your questions at hand.  It may take some back and forth work that will best be done as forum question.  I have some questions about what you see and want to keep a lengthy discussion out of the article comments.  if you do open a question, you could post a link here and I can go check it out.
This script will sweep a range of IP addresses (class c only, and report to a log the version of office installed.

What it does:
1.)      Creates log file in the directory the script is run from (if it doesn't already exist)
2.)      Sweeps IP range using a For Next loop
3.)      Gets computer name from IP address for better logging
4.)      Gets office path from registry
5.)      Gets office version
6.)      Reports version (2000-2010) using Select Case

What you have to do to make it work:
1.)      Change "BaseIP" to match your IP subnet
2.)      Change "StartIP" to the first host in the range to scan
3.)      Change "EndIP" to the last host in the range to scan
4.)      Run the script using CScript.  
5.)      Alternately you can comment out the two "WScript.Echo" entries within the main
and run it using WScript which will create the log but gives no information while running except a "Script Complete" notification.  Personally, I like to watch it run so I leave the echo's in the loop and run it cscript.

That’s it!  Setup your IP information and run it…get some info about your Office environment.

I used this as part of an effort to deploy some software to clients with certain versions of office.  Different versions of office got different versions of 3rd party add-on's installed.  Throw in a couple subs to make this a really powerful deployment tool.

Here is a sample of the log output:
8/3/2011      6:19:22 PM      No response
8/3/2011      6:19:24 PM      …

Expert Comment

by:SR Zak
Sorry that does not work.

Is there a manual way or easier way. using MMC maybe?

Expert Comment

by:Laurent Mander
Hi, I've corrected and extended the script, enjoy \o/

Version 2.0
This is pretty cool.  The purpose of this VB Script is to help you document where JAR (Java ARchive) files and specifically java class files are located so that you can address issues seen with a client or that you can speak intelligently with a developer when researching a customer issue.  Most times when documenting issues, it is helpful to know where the problem exists and if you are able to replicate the issue: sounds like QA Testing for bug reports, doesn't it?  

It can help with research and documentation for issues seen when working cases for Java and Tomcat type of files. You will find when supporting Java products is that you can take a jar file and simply treat it as a zip file.  What is good about this is that you can put the information from your findings and the documented results in to  your Support Desk or SharePoint site so that you can search the information for what class under which jar file is giving the user a challenge..  I cannot take full credit for the ideas behind the process as I have borrowed pieces from http://www.robvanderwoude.com and I am using a COM Object (.dll) from http://www.xstandard.com to look inside these jar files.

Here is an example that you may see in real life - In troubleshooting, you may see a message like:
Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Connection reset by peer: socket write error
      at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
OWASP: Avoiding Hacker Tricks
LVL 19
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

When it comes to writing scripts for a Client/Server computing environment it is essential to consider some way of enabling the authentication functionality within a script. This sort of consideration mainly comes into the picture when we are dealing with remote computer administration scripts.

Many of us who are working on VBScripts and automation tasks might have encountered a need for prompting the user to provide the login credentials (Username/Password), to perform some task during script execution. It's not always safe to include the logon credentials as part of the code itself because these files are in a plain text format and anyone can read it.

If you’re running Windows XP or Windows Server 2003, you can use ScriptPW (a COM object found only in those two versions of Windows) to mask passwords from the command line. Here’s a sample script that creates an instance of the ScriptPW.Password object and then uses the StdOut Write method to request that the user enter a password:

Set objPassword = CreateObject("ScriptPW.Password") 
WScript.StdOut.Write "Please enter your password:" 

strPassword = objPassword.GetPassword() 
Wscript.Echo "Your password is: " & strPassword

Open in new window

When you run this script, the message "Please enter your password:" appears on the screen. At that point, the script will pause and wait for you to type in a password; you simply type the password and press ENTER. This line of code will then grab the password and store it in the variable strPassword:

strPassword = objPassword.GetPassword()

Open in new window

LVL 14

Expert Comment

nice! will keep in my toolbox...

Expert Comment


I am trying to use this script but when the browser window opens, the script exits.

'The interface is unknown' at line 59

Do Until objBrowser.ReadyState = 4

Can anyone help?


During my participation as a VBScript contributor at Experts Exchange, one of the most common questions I come across is this:
"I have a script that runs against only one computer. How can I make it run against a list of computers in a text file?"
This article will provide you with an understanding of what you need to do to get this done, and also throw in some helpful features to make things a bit "neater".

Where Do We Start?

We should start with a script that presents the problem; one that only runs against one computer.  Here is a simple script that will retrieve the free space available on C Drive of the local computer.  The free space information is gathered using WMI, Windows Management Instrumentation.  WMI provides access to many classes that store information about the system and its settings and state.

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'")
For Each objItem In colItems
   dblFreeSpace = Round(objItem.FreeSpace / 1024 / 1024, 3)
WScript.Echo dblFreeSpace & " MB Free"

Open in new window

There's not much to this script, but here’s how it works.
strComputer = "." refers to the local computer, so the WMI connection will be made to the computer that the script is running on.
objWMIService is the user defined variable name that represents the WMI Connection we are creating.  We can then use that connection to execute the WMI queries we need to use.
The GetObject call is the method that actually creates the WMI connection, and winmgmts represents the WMI Service.
{impersonationLevel=impersonate} is the default security moniker, which doesn't need to be specified, but I like to keep it in, just for completeness.

LVL 65

Author Comment

That looks like it might just be that you have a blank line at the end of your input file.  Remove any blank line at the end and try again.


Expert Comment

Great Job Rob. The code is working fine. Sorry for the delayed reply.

Thanks for your help.

I met Paul Devereux (@pdevereux) today when I responded to his tweet asking “Anybody know how to automate adding files from disk to a folder in #outlook  ?”.  I replied back and told Paul that using automation, in this case scripting, to add files to Outlook is pretty simple.  Paul and I exchanged a few more tweets and from them I learned that he has the following requirements for this process:

    * Read the file names from a DB table.
    * The DB could be MS Access or SQL Server.
    * Files could be of any type.
    * Needs to work with Outlook 2003, 2007, and 2010.
    * The process needs to run from outside of Outlook.

The code for handling this is below. It’s pretty simple and I added a number of comments to help both you and Paul figure out what it’s doing.  The script uses Microsoft’s ADODB technology to connect to and read a table in the DB.  For each row in the table the script creates an Outlook DocumentItem object, a file within an Outlook folder, fills in some information about it, and saves it into an Outlook folder.  In this case I used the inbox, but Paul can modify the code to save it into the folder of his choice.  Paul will also need to set the ADODB connection string to connect to his database.  He can use Connectionstrings.com to find the correct string for either Access or SQL Server.  Finally, he will also need to edit the field names to match those that appear in his table.

The code is written in VBScript making it easy for Paul to edit …
Well hello again!  Glad to see you've made it this far without giving up.  In this, the fourth installment of my popular series, I'm going to cover functions and subroutines, what they are, and why they are useful.  Just in case you stumbled onto the series in the middle, please take a few minutes and review the previous installments here:

Part 1
Part 2
The Missing Prequel
Part 3

So..  Now that we are once again on the same page, let's get to it.

Functions and subs are basically the same thing, with only a single difference:  A function returns a value, but a sub does not.  Chances are you've already used functions and subs without realizing it.  When you say
 Set oOU = GetObject("LDAP://...")

Open in new window

GetObject is actually a function that returns the object you have given the ADSPath to.  That function is one that is built-in, you don't actually see the code behind it.

But, what is a function?  Why would I want one?  What would I do with one?  Well, imagine you had this list of numbers.  You needed to take each number, multiply it by something else, then concatenate it to a string, and then echo what it is.  You could go like this:

x = 1
data = cstr(x * 2) & " apples"
wscript.echo data
x = 2
data = cstr(x * 2) & " apples"
wscript.echo data
x = 3
data = cstr(x * 2) & " apples"
wscript.echo data

Open in new window

You can see that it's mostly the same code repeated.  So...

Process 1
Process 2
Process 3

Sub Process(x)
    data = cstr(x * 2) & " apples"
    wscript.echo data
End Sub

Open in new window

Welcome, welcome!  If you are new to the series and haven't been following along, please take a brief moment to review the first three installments:

Part 1
Part 2
The Missing Prequel

Ok, so now that we are all up to speed and on the same page, let's get on with the learnin', shall we?  This article will focus on manipulating the Windows filesystem using the VBS FileSystemObject.   Why do we want to do this?  Well, as I'm sure you know, lots of times users need things done on file servers, or you need to create home directories for new users, or copy base profiles, all sorts of stuff.  If you get it all into one script, it saves lots of time in the long run.  So, to get at the filesystem:

Set oFS = CreateObject("Scripting.FileSystemObject")

Open in new window

So, now we have a handle that we can use to access the filesystem - oFS.  What can we do with it?

Set oFS = CreateObject("Scripting.FileSystemObject")
Set oFile = oFS.CreateTextFile("c:\myfile.txt")

Open in new window

If you run that, you'll get a text file created in the root of your C: drive called myfile.txt, and it will contain one line that says


Easy, huh?  This is useful for when you are debugging applications that have a LOT of data in them (like arrays of over 1000 objects), and echoing all of that data to the screen simply isn't practical.  Why do I say that this is only useful for debugging?  Well, the CreateTextFile method will overwrite any text file that is there, so you'll have a fresh one every time, with only the data from the last run.  If you wanted to append to a text file, then we can use another filesystem method, FileExists:

Open in new window

Hello again, all.  For those of you that have been following along, you'll know that this is my third article on this topic (though it is not Part III).  This article is sort of remedial, and probably the topic with which I should have started the series.  VBScript For Windows System Administrators Part 1  VBScript For Windows System Administrators Part 2
So...  Why am I calling this the missing prequel, and "What's with the myths?" you may be wondering?  Well, from reading code on here, and seeing code that peers have written, and from seeing code that pupils have written (I've taught dozens of employees & co-workers how to code), I've seen lots of good things, and lots of not-so-good things.  This article will focus more on the latter.


FALSE.  The fact of the matter is that VBS is an extremely flexible scripting language, and will create variables on the fly.  For example, simply saying:

x = 8

Open in new window

creates a variable called "x" and assigns it an integer value of 8.  The only exception to this is if "Option Explicit" is used.  In that case, you MUST DIM all variables.  This is useful when you are writing VERY large scripts, and want to eliminate typos.  How is this useful?  Since VBS will happily create variables for you as you use them, consider:

VariableA = 24
VariableB = 24
VariableC = VariableA + VaraibleB
WScript.Echo VariableC

Open in new window

LVL 93

Expert Comment

by:Patrick Matthews
When I look back at some of the scripts I wrote in the beginning, I often find myself wondering "What the HECK was I thinking?!?"

Amen, brother!

Every once in a while, I have to go back an look at code I wrote circa 2001-2005--in other words, before I joined EE, and into the first year or two of my arriving here--and I can't believe I actually signed my name to it.  It works, almost all the time, anyway, but I can't imagine what made me think the techniques used were good ideas...

Expert Comment

Thank you!
Welcome back!  My apologies for taking so long to write part two of this series; it's been a long time coming!  As I promised in Part 1, this article will focus on how to locate those elusive AD properties that you are searching for.  Why is this useful?  Well, for instance, did you know that each user account in AD has an Employee ID field?  Don't go look, you can't find it in the regular Active Directory Users & Computers (hereafter referred to as ADU&C) GUI.  But, I'll show you how to find, and configure, this field and many, many more.

First things first.  In order to follow along, you're going to need an AD environment you can use as a sandbox.  That's right, kids, don't run this stuff on your production network.  BAD THINGS can happen!  I remember an incident about 10 years ago when I deleted every single user in AD.  Luckily, the company hadn't yet switched to AD (it was a clean migration from NT4 to 2000, not an upgrade), so I just re-ran the script to recreate all the users.  But had that been production, I'm sure I would have spent some time brushing the dust off my resume!

So, to get started, the main tool we will be using here is ADSIEdit.msc.  This is a free tool, and is included with the Windows Support tools.  Download the package, install it, and then just click Start -> Run and type "adsiedit.msc" and viola!  There it is.  WARNING:  BE CAREFUL!  Anything you modify in here directly changes Active Directory, and can cause corrupted objects, or other …
Script to copy or move mouse-selected collection of files plus targets referenced by shortcuts (.lnk)

The purpose of this article is to help illuminate the real challenges and options available (where they may exist) for utilizing simple scripting methods for handling copying/moving of file system objects, ...overcoming the limitation for interfacing with the Windows Clipboard imposed on scripts and the command processor interface (command line).

How would you like to be able to create a script that allows you to simply
 arbitrarily select some files within a Window (directory)
 including shortcuts
 and copy or move all the targets, i.e., the real files in the directory, and the real files the shortcuts point to (but not the shortcuts themselves)
 ...to another directory location?
Heretofore, the only way via simple scripting I have seen to do this is to create a list from a selection and use that to make a batch you then use for copying or moving the files.  (pita)

The only other way I can think of to otherwise facilitate this is by creating an application, or DLL Wrapper, or shell extension, for interfacing to the system clipboard (which I really want to do for my 2nd dll project)... however, all I want to do right now is use a "SIMPLE" script...
-- what to do??

***Well, I finally figured out a way to do this with a very simple script, although it still must rely on a small outside helper.


Author Comment

A gentleman, stoyanov, who was unable to register, wrote the following to me, so I figured I would post it for posterity.  I do not have time to test viability myself, but it was nice he took the time to write...


I found this one:


could be useful registering context menu for your script.

And also that "Send to Toys" has a settings called "Resolve shortcuts" (which works little bit strange, but hope it will go better), and this option works also for folders.

Sorry for writing you a personal mail, but i can't register to experts-exchange forum.

Thanks for shared knowledge :)

Wish you all best.

Expert Comment

by:Amanda Smedley
I use the Q-DIR (alternative windows explorer) and the Program or Quick-Links buttons to create menus.
Q-Dir Software Page
It runs my scripts/batches/powershell files all very well.
When developping tools to manage simple tasks in an enterprise or a network, I often use vbscripts
I wanted a way to centralize all thoses scripts, in a user friendly interface that can zoom, print and copy paste easily

As a network administrator, I do not have the time to program theses tools in visual basic

That is a VBS script that use internet explorer as user interface, divided in 3 frames
control (LEF)
input (MID ok i could have called this one top)
output (BOT)
right now it's just an interface where you can:
change the control buttons
and insert your own scripts for each button to ask for certain inputs and execute a command
creation of a user in LDAP
creation of folders for a new contrat that have just oppened
setting permissions for folders
manage a small access or sql database like a phone list
creation of public folders in outlook ora sharepoint folder in outlook
All these things i will add in the futur updates
They are currently in some of my scripts that are not merged yet with this interface


1. add a button for your script

first part is to add a button to call your scriptit can be done here: (line 86 approx)

ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutdes(x)="test2 my own script"

Open in new window


arabutnam - array of button names
name of the button is just a string (preferably without space or uppercase letters)
arabutdes - description of the button
text inside the button
LVL 12

Author Comment

by:Serge Fournier
i do nto know if we can link blog here but here it is:


i am converting all my web interface code from wsh (windows host script) to visual basic 2010

so all the techniques here have been converted
1 using internet explorer as web interface in vb.net
2 using database mdb
3 handling key event
4 handling click event

LVL 12

Author Comment

by:Serge Fournier
With the arrival of internet explorer 10 my web interface was displaying empty frames

Here is the correction you must apply to 3 objects:

Just search for this line:
      set flef = oie.document.frames("left").document

It's when the frames objects are created
Replace with the code below with a condition if it's explorer 10 or before

'=== get version
fileversion = objFSO.GetFileVersion("C:\program files\internet explorer\iexplore.exe")
finddot = instr(fileversion,".")
fileversion2 = left(fileversion,finddot-1)

if fileversion2 = "10" then
	'=== ie10 frame access
	set flef = oie.parent.document.getElementByid("left").contentdocument
	set fmid = oie.parent.document.getElementByid("middle").contentdocument
	set fbot = oie.parent.document.getElementByid("bottom").contentdocument
	set flef = oie.document.frames("left").document
	set fmid = oie.document.frames("middle").document
	set fbot = oie.document.frames("bottom").document
end if

Open in new window

Become a Microsoft Certified Solutions Expert
LVL 19
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

In this article we want to have a look at the directory attributes which are used by Microsoft to store the so called Security Identifiers (SID). These SIDs plays an important role in delegating and granting permissions and in authentication of trustee holders against the system. Important Active Directory attributes are stored as SIDs: objectSid, sIDHistory, tokenGroups. There also the wellknown SIDs which represents entries in permission configurations liek this: SYSTEM, ANONYMOUS, EVERYONE and so on...

How can we handle these SIDs in a VBScript? Basically, SID attributes can be read with LDAP/ADSI as Octet Strings. And: They are binary data with a rather complex structure.

This structure is explained in the Microsoft Technet documentation:

or even better in the SelfADSI tutorial:

The internal structure of a SID is based mainly on a so called Identifier Authority data block and several Sub-Authority data blocks. The SID starts with a leading Revision byte, followed by a byte which indicates the count of the Sub-Authority blocks. Then there is the Identifier Authority with six bytes (normal byte order), and after that the Sub-Authority blocks (4 bytes each wit a reverse byte order (Big Endian). So this is the SID:

1 byte Revision (always 1)
1 byte Sub-ID block count (for normal AD object SIDs always 5, for wellknown SIDs 1)
This is an addendum to the following article:

Acitve Directory based Outlook Signature

The script is fine, and works in normal client-server domains.

If you want to use the script on a Citrix or Terminal Services server, the IsOutlookFunction stops if anyone on the server has Outlook running.  In this case, you want to check only if Outlook is running for the current user:

I changed the code as follows:

Function IsOutlookRunning()
	strComputer = "."
	strQuery = "Select * from Win32_Process " & _
	"Where Name = 'OUTLOOK.EXE'"
	Set objWMIService = GetObject("winmgmts:" _
	& "{impersonationLevel=impersonate}!\\" _
	& strComputer & "\root\cimv2")
	Set colProcesses = objWMIService.ExecQuery(strQuery)
	For Each objProcess In colProcesses

=>	    colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)
		If UCase(objProcess.Name) = "OUTLOOK.EXE" Then
=>		    If objSysInfo.Username = strNameOfUser Then		                             IsOutlookRunning = True
=>		   Else
=>		        IsOutlookRunning = False
=>		    End if
			IsOutlookRunning = False
		End If
End Function

Open in new window

This script checks for a running "Outlook.exe" process for the current user.

I found the code that I added from the Question/Answer "Hey, Scripting Guy! Blog" website.

Most of the time Google is your friend in finding the right code--you only have to know how to incorporate it into you're own scripts.

I used the GetOwner
LVL 56

Expert Comment

by:Mark Wills
Good Tip ! Thanks, will keep this one handy...
Recently I finished a vbscript that I thought I'd share.  It uses a text file with a list of server names to loop through and get various status reports, then writes them all into an Excel file.  Originally it was put together for our Altiris server environment, but it is easily adaptable to whatever purpose you'd have.  Really, only the last column in the report "Number of Clients" is Altiris specific, the rest is totally open ended.

Note:  The text file with the server names needs a line feed between the server names.


Not:  Server1, Server2, Server3

The things I have the script report are:

Server Name
Operating System + Service Pack
SQL Version
IP Address
Logical Disk
Number of Clients

Note:  The Number of Clients is purely for Altiris.
'I use the file extension XLSX because I have Office 2007, 
'for older versions change it to XLS
'Unless you specify a folder path (ie: C:\Serverdata\ServerStats.xlsx) 
'the file will default to your My Documents folder.
strExcelPath = "ServerStats.xlsx" 
'Access FSO to handle text
Set ObjFSO = CreateObject("Scripting.FileSystemObject") 
'This text file holds the list of servers to get status from.
Set objServerList = objFSO.OpenTextFile("ServerList.txt") 
'Create an Excel instance to write data too
'The script could be easily modified to write the data sets to 
'a SQL database, text file, csv or whatever.
Set objExcel = 

Open in new window


Expert Comment

How would you modify the script to show number of physical disks and could you take out the Altiris information and replace it with SCCM client?
LVL 65

Expert Comment

Hi, I've added a WMI Time Out that mehuljadeja requested, using a function I wrote here:

I have also added the number of physical disks to the output.

I don't know about the SCCM output. You probably can.  If you can find some code to give you SCCM output, we could plug that in.


If LCase(Right(Wscript.FullName, 11)) = "wscript.exe" Then
    strPath = Wscript.ScriptFullName
    strCommand = "%comspec% /c cscript  """ & strPath & """"
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run(strCommand), 1, True
End If
Const WMITimeOutInSeconds = 10
'I use the file extension XLSX because I have Office 2007, 
'for older versions change it to XLS
'Unless you specify a folder path (ie: C:\Serverdata\ServerStats.xlsx) 
'the file will default to your My Documents folder.
strExcelPath = "ServerStats.xlsx" 
'Access FSO to handle text
Set ObjFSO = CreateObject("Scripting.FileSystemObject") 
'This text file holds the list of servers to get status from.
Set objServerList = objFSO.OpenTextFile("ServerList.txt") 
'Create an Excel instance to write data too
'The script could be easily modified to write the data sets to 
'a SQL database, text file, csv or whatever.
WScript.Echo "Starting Microsoft Excel..."
Set objExcel = CreateObject("Excel.Application") 
'Excel commands to open a new workbook and add a worksheet to it
Set objWB = objExcel.Workbooks.Add
objExcel.DisplayAlerts = False
While objWB.Sheets.Count > 1
objExcel.DisplayAlerts = True
'Sets the worksheet as the active sheet to use.  
'If using more than one sheet, 
'change the active sheet by changing the number in the ()
Set objSheet = objWB.Worksheets(1) 
'This section writes the Header information to the worksheet 
'and sets the font for them to bold
objSheet.Range("A1:N1").Font.Bold = True
objSheet.Cells(1, 1).Value = "Server Name"
objSheet.Cells(1, 2).Value = "Location"
objSheet.Cells(1, 3).Value = "Operating System"
objSheet.Cells(1, 4).Value = "SQL Version"
objSheet.Cells(1, 5).Value = "Serial Number"
objSheet.Cells(1, 6).Value = "Manufacturer"
objSheet.Cells(1, 7).Value = "Model"
objSheet.Cells(1, 8).Value = "Memory"
objSheet.Cells(1, 9).Value = "# of Processors"
objSheet.Cells(1, 10).Value = "Processor Type"
objSheet.Cells(1, 11).Value = "IP Address"
objSheet.Cells(1, 12).Value = "No of Physical Disks"
objSheet.Cells(1, 13).Value = "Logical Disk"
objSheet.Cells(1, 14).Value = "Number of Clients" 
'This integer will be the row that data is written to in Excel.  
'If you didn't have a header row or more than one header row, 
'you would modify the number to whichever row to start writing to.
Row = 2 
'Starts the Loop of reading through the text file containing the server names.
Do While Not objServerList.AtEndOfStream
	'Sets the computer variable for the server name read out of the text file
	strComputer = objServerList.ReadLine 
	If Trim(strComputer) <> "" Then
		WScript.Echo "Connecting to " & strComputer
		If Ping(strComputer) = True Then
			strReturn = TestWMIConnection(strComputer, WMITimeOutInSeconds)
			If strReturn = "success" Then
				'In case one of the servers has WMI errors, I added a Resume here.
				On Error Resume Next
				'Connects to remote computer and creates a WMI instance
				Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
				'Log failed connections
				If Err.Number <> 0 Then
					Set objLogOut = objFSO.OpenTextFile("ServerList.log",2, True)
					objLogOut.Write("Connection failed on:  " & strComputer & " on " & Now & vbCrLf)
					WScript.Echo "WMI Connection failed to " & strComputer
					'Continue with script if no error encounters
				ElseIf Err.Number = 0 Then
					WScript.Echo "Connection successful. Retrieving information..."
					'Writes the server name to the first column
					objSheet.Cells(Row,1).Value = strComputer 
					'Uses a Case function to parse through the strComputer and write the location specified
					strSite = ""
					Select Case strComputer
						Case "AltirisNS1" strSite = "Notification Server"
						Case "Package1" strSite = "Package Server USA"
						Case "Package2" strSite = "Package Server Asia"
						Case "Deployment1" strSite = "Deployment Server USA"
						Case "Deployment2" strSite = "Deployment Server Asia"
						Case Else strSite = "Unknown Site"
					End Select	
					objSheet.Cells(Row,2).Value = strSite 
					'Gets OS   Service Pack
					WScript.Echo vbTab & "...OS Details..."
					Set colOSes = objWMIService.ExecQuery("Select Caption,ServicePackMajorVersion,ServicePackMinorVersion from Win32_OperatingSystem")
					For Each objOS in colOSes
						objSheet.Cells(Row,3).Value = objOS.Caption & " SP " & objOS.ServicePackMajorVersion & "." & objOS.ServicePackMinorVersion
					'Get SQL Server Version
					'If you are checking a server with an offloaded database,
					'you will need to add it into the If statement so you pull data 
					'from the correct SQL Server 
					WScript.Echo vbTab & "...SQL Server Version..."
					If strComputer = "AltirisNS1" Then
						strDBServerName = "AltirisSQL"
						strDBServerName = strComputer
					End If 
					'Connects to the SQLDMO Object to pull the version data
					Set objSQLServer = CreateObject("SQLDMO.SQLServer")
					objSQLServer.LoginSecure = True
					objSQLServer.Connect strDBServerName
					strVersionInfo = objSQLServer.VersionString 
					'The VersionString data that is returned is very long
					'and not well suited to write into Excel.
					'Here is what the VersionString looks like normally: 
					'Microsoft SQL Server 2005 - 9.00.3054.00 (Intel X86) 
					'	Mar 23 2007 16:28:52 
					'	Copyright (c) 1988-2005 Microsoft Corporation
					'	Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
					'In order to cut the string down to something more concise (Version & Edition)
					'a Split/Trim loop is used to gather the relevant data.
					'(Thank you to RobSampson at ExchangeExperts for his help with this part) 
					For Each strLine In Split(strVersionInfo, VbLf)
						If InStr(strLine, "SQL Server") > 0 Then
							strSQLVer = Trim(Left(strLine, InStr(strLine, " -") - 1))
						ElseIf InStr(strLine, "on Windows") > 0 Then
							strSQLEd = Trim(Left(strLine, InStr(strLine, "on Windows") - 1))
						End If
					objSheet.Cells(Row,4).Value = strSQLVer & "-" & strSQLEd 
					'Get Serial Number
					WScript.Echo vbTab & "...Serial Number..."
					Set colItems1 = objWMIService.ExecQuery("SELECT SerialNumber FROM Win32_BIOS",,48)
					For Each oItem In colItems1
						objSheet.Cells(Row,5).Value = oItem.SerialNumber
					'Gather several Computer System data sets.
					'For this script, I grab Manufacturer, Model, 
					'RAM (rounded down to # of gigs), and Processor count.
					WScript.Echo vbTab & "...Memory Details..."
					Set colSettings = objWMIService.ExecQuery("Select Manufacturer,Model,TotalPhysicalMemory,NumberOfProcessors from Win32_ComputerSystem")
					For Each objComputer in colSettings
						objSheet.Cells(Row,6).Value = objComputer.Manufacturer
						objSheet.Cells(Row,7).Value = objComputer.Model
						objSheet.Cells(Row,8).Value = Round((objComputer.TotalPhysicalMemory/1000000000),4)
						objSheet.Cells(Row,9).Value = objComputer.NumberOfProcessors
					'Get Processor Information
					WScript.Echo vbTab & "...Processor Details..."
					Set colItems = objWMIService.ExecQuery("Select Name from Win32_Processor",,48)
					For Each objItem in colItems
						objSheet.Cells(Row,10).Value = objItem.Name
					'Get the IP Address
					WScript.Echo vbTab & "...IP Addresses..."
					Set colIPItems = objWMIService.ExecQuery("SELECT IPAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
					For Each objIPItem In colIPItems 
						strIPAddress = Join(objIPItem.IPAddress, ",")
						If strIPAddress <> "" Then objSheet.Cells(Row,11).Value = strIPAddress
					'Get Logical Disk Size and Partition Information
					'In order to deal with multiple disks and partitions,
					'the list of HDD information is pulled into an array
					'which is looped through to get the information from each HDD
					'and then a Join function writes them all as a single string 
					WScript.Echo vbTab & "...Hard Disk Details..."
					intPhysicalDisks = 0
					Set colDisks = objWMIService.ExecQuery("Select * From Win32_DiskDrive")
					For Each objDisk In colDisks
						intPhysicalDisks = intPhysicalDisks + 1
					objSheet.Cells(Row,12).Value = intPhysicalDisks
					Dim arrDisks()
					intArr = 1
					Set colDisks = objWMIService.ExecQuery("Select DeviceID,FileSystem,Size,FreeSpace from Win32_LogicalDisk Where DriveType = 3")
					For Each objDisk In colDisks
						ReDim Preserve arrDisks(intArr) 
						arrDisks(intArr) = "DISK " & objDisk.DeviceID & " (" & objDisk.FileSystem & ")" & Round((objDisk.Size/1000000000),4) & " GB (" & Round((objDisk.FreeSpace/1000000000)*1.024,4) & " GB Free Space)" & " "
						intArr = intArr + 1
					'I used a " | " to seperate each disk
					objSheet.Cells(Row,13).Value = Join(arrDisks," | ") 
					WScript.Echo vbTab & "...Altiris Client Details..."
					'Get Number of Altiris Clients
					'This is purely something for use with Altiris servers,
					'but again, the function can be modified for other purposes 
					'Creates an ADODB object to access SQL servers
					Set CnnSQL=CreateObject("ADODB.Connection") 
					'Again, just like with getting the version information,
					'if you have an offloaded database, you need to use this
					'If...Then...Else... loop to point to the correct server.
					'For the query itself I just took the query to list clients
					'and added a COUNT SQL function to the query. 
					If strComputer = "AltirisNS1" Then
						CnnSQL.Open "Provider=SQLOLEDB;DATA SOURCE=IRVSQL51;INITIAL CATALOG=Altiris2;Integrated Security=SSPI"
						Set RS = CreateObject("ADODB.Recordset") 
						Set RS = CnnSQL.Execute("SELECT COUNT (guid) FROM vComputerResource WHERE IsManaged=1")
						CnnSQL.Open "Provider=SQLOLEDB;DATA SOURCE=" & strComputer & ";INITIAL CATALOG=eXpress;Integrated Security=SSPI"
						Set RS = CreateObject("ADODB.Recordset") 
						Set RS = CnnSQL.Execute("SELECT COUNT(name) FROM computer")
					End If
					objSheet.Cells(Row,14).Value = RS(0)
					Set RS = Nothing
					Set CnnSQL = Nothing  
				'This ends the Loop where the server name was read from the text file
				'and adds a count to the Row integer so data will now write on the next row in Excel 
				End If
				Row = Row + 1
			ElseIf strReturn = "failed" Then
				Set objLogOut = objFSO.OpenTextFile("ServerList.log",2, True)
				objLogOut.Write("Connection failed on:  " & strComputer & " on " & Now & vbCrLf)
				WScript.Echo "WMI Connection failed to " & strComputer
				'Continue with script if no error encounters
				Set objLogOut = objFSO.OpenTextFile("ServerList.log",2, True)
				objLogOut.Write("Connection time out on:  " & strComputer & " on " & Now & vbCrLf)
				WScript.Echo "WMI Connection time out on " & strComputer
				'Continue with script if no error encounters
			End If
			'Computer did not respond to Ping
			Set objLogOut = objFSO.OpenTextFile("ServerList.log",2, True)
			objLogOut.Write("Ping failed on:  " & strComputer & " on " & Now & vbCrLf)
			WScript.Echo "Ping failed to " & strComputer
		End If
	End If


'Saves the Excel workbook and closes everything up
objExcel.DisplayAlerts = False
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.DisplayAlerts = True
'Added in a Done echo because the script can take several minutes 
'depending on how many servers that are being queried.
WScript.Echo "Done"

Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 4 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
		Ping = False
	End If
End Function

Function TestWMIConnection(strComputer, intTimeOutInSeconds)
   ' Function written by Rob Sampson - 12 Jan 2011
   ' Experts-Exchange volunteer: http://www.experts-exchange.com/M_3820065.html
   ' Return strings from this function are in lower case, and consist of:
   ' "success": WMI Connection successful
   ' "failed": WMI Connection failed
   ' "time out": WMI Connection attempt timed out

   Set ObjFSO = CreateObject("Scripting.FileSystemObject")
   strTempScript = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "TempWMITestToBeDeleted.vbs"

   Set objTempFile = objFSO.CreateTextFile(strTempScript, True)
   objTempFile.WriteLine "On Error Resume Next"
   objTempFile.WriteLine "Set objWMIService = GetObject(""winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2"")"
   objTempFile.WriteLine "If Err.Number = 0 Then"
   objTempFile.WriteLine vbTab & "WScript.StdOut.Write ""success"""
   objTempFile.WriteLine "Else"
   objTempFile.WriteLine vbTab & "WScript.StdOut.Write ""failed"""
   objTempFile.WriteLine "End If"

   Set objShell = CreateObject("WScript.Shell")
   Set objExec = objShell.Exec("wscript " & objFSO.GetFile(strTempScript).ShortPath)
   intSeconds = 0
   While objExec.Status = 0 And intSeconds <= intTimeOutInSeconds
      WScript.Sleep 1000
      intSeconds = intSeconds + 1
   If objExec.Status = 1 Then
      strReturn = objExec.StdOut.ReadAll
      On Error Resume Next
      On Error GoTo 0
      strReturn = "time out"
   End If
   objFSO.DeleteFile strTempScript, True

   TestWMIConnection = LCase(strReturn)
End Function

Open in new window

Unlike scripting languages such as C# where a semi-colon is used to indicate the end of a command, Microsoft's VBScript language relies on line breaks to determine when a command begins and ends. As you can imagine, this quickly results in messy code, with declarations for variables, and then actually setting those variables, using up two lines, like the below.

Dim myVariable
Set myVariable = Server.CreateObject("MyObject")
Dim myString
myString = Request.ServerVariables("name")
Dim myInt
myInt = 44-6

Open in new window

Fortunately, there is help at hand. A little known trick to many scripting in VBS is the power of the colon - this simple character enables you to place multiple commands on a single line, replacing the location where you would place a line break with a colon.

Using this trick, my code above now looks like:
Dim myVariable: Set myVariable = Server.CreateObject("MyObject")
Dim myString: myString = Request.ServerVariables("name")
Dim myInt: myInt = 44-6

Open in new window

As you can see, this code is a lot cleaner; the colon character has been used to replace the line break between a variable declaration and setting that variable's value, enabling easier reading of code for both yourself and future developers.

LVL 39

Expert Comment

bivesst2:  Make sure you click the good old "Yes" it was helpful link then to give TigerMatt his props!
LVL 76

Expert Comment

I might add that you should use reasonable spacing if you combine commands on one line. In above code, it would look like

Dim myVariable:   Set myVariable = Server.CreateObject("MyObject")
Dim myString:       myString = Request.ServerVariables("name")
Dim myInt:             myInt = 44-6

which should attract the reader to the important parts, which are assignments.
You can even align by the equal sign by using more spaces in VB Script, but in VBA it does not work because of the automatic formatting the editor applies.
Welcome to part one of a multi-part tutorial series, VBScript for Windows System Administrators.  The goal of this series is to teach non-programmers how to write useful VBS code to automate their environment, and perform tasks faster, and in a more consistent fashion.  I am not a professional programmer, and I am not a professional author.  I'm just an admin who has found that VBS has made my life much, much easier, and I'd like to share that with you.  I hope you enjoy this reading this series as much as I've enjoyed writing it.

As Admins, a lot of our job revolves around managing users, user settings, and everything else in Active Directory.  The majority of this series will focus on that.  I will also be going into reading/writing text files, and working with Excel automation.  For the sake of staying on topic, I'm going to make a few assumptions:  You know your way around AD pretty well, and understand basic concepts such as Organizational Units, Containers, Users, Groups, Contacts, etc.  If you need any help understanding those topics, please take a moment to browse this site before continuing:  http://technet.microsoft.com/en-us/library/cc780336.aspx

Ok.  For the duration of this series, we will be working with a simple forest/domain AD.  One forest, one domain.  The FQDN of the domain is mydomain.local, and the AD structure looks like this:

LVL 26

Expert Comment

by:Ron Malmstead
May I suggest WMI Code creator for anyone who is learning how to write administrative scripts.

LVL 26

Expert Comment

I <b>HIGHLY</b> recommend WMI Code creator as well as The Do It Yourself kit, which has scripting tools written in vbscript,, KIXtart REXX and other languages.
Often times network admins need to run domain logon scripts for seperate subnets, but also for a seperate set of computers within that subnet.  In this circumstance, configuring Active Directory Sites and Services then linking a GPO to site/subnet might not be an option.

So now what ?

This is a real world example of this situation and my accepted solution: http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Server/Q_22746765.html?sfQueryTermInfo=1+locat+login+script+vb

This is the solution you can employ so that your logon scripts can identify the subnet a computer exists on...in order to decide whether to run or terminate.  Currently the script is only designed for class C network identification.

You need two things to make this work...
1) The attached vbscript (paste into notepad and save as *.vbs)
2) A program called setx.exe (Found in the MS Resource kit - http://www.microsoft.com/downloads/details.aspx?FamilyID=DC2D3339-8F36-4FBA-A406-2A2A2AD7208C&displaylang=en)

Once you have successfully employed this method....you can use the conditional code in your logon scripts using the subnet as a system variable.
Example: The subnet is 192.168.6, which was set as a variable %IPNETID%, and I want a …

Expert Comment

@Echo off
Set Prompt=$D$T  $B$G
::Deployment Script
::Version: 11.3
::Created by: DuaneMizell (http://www.experts-exchange.com/M_4688963.html)
::Created: 12/2009
::Modified: 03/2012
for /f "tokens=2 delims=[]" %%i in ('pathping -p 1 -q 1 -4 %computername%') do set IP=%%i
for /f "tokens=2 delims=." %%i in ('echo %IP%') do set OCTET2=%%i
set strIP=%OCTET2%
if ["%strIP%"]==["14"] (
echo 14th Floor IP address...
goto 14Office)
if ["%strIP%"]==["15"] (
echo 15th Floor IP address...
goto 15Office)
if ["%strIP%"]==["16"] (
echo 16th Floor IP address...
goto 16Office)
if ["%strIP%"]==["18"] (
echo 18th Floor IP address...
goto 18Office)
if ["%strIP%"]==["23"] (
echo 23trd Floor IP address...
goto 23Office)
if ["%strIP%"]==["24"] (
echo 24th Floor IP address...
goto 24Office)
if ["%strIP%"]==["25"] (
echo 25th Floor IP address...
goto 25Office)

Echo Not a good IP address: 10.%strIP%.x.x (This computers IP address is: %IP%) Automatically pulling files from home office!!!

goto DefaultInstall

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer1\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer2\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer3\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer4\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer5\SomeFolder
goto Install

@Echo On
::DO: Stuff

set InstallPath="\\SomeServer6\SomeFolder
goto Install

@Echo on
::DO: Stuff

set InstallPath="\\SomeServer00\SomeFolder
goto Install

rem Insert install code here. Use the variable "%InstallPath%" (without quotes)  to call the local office path to \\SomeServerX\SomeFolder
rem Example for an installation of Whatever.MSI located in \\SomeServerX\SomeFolder:
rem msiexec /package %InstallPath%\SomeFolder\Whatever.MSI" /passive /norestart
REM Insert install code below:

goto eof
Set Prompt=$P$G
echo Done!
LVL 44

Expert Comment

by:Steve Knight
Another easy way to get the parts of IP address during the login script, along similar lines:


@echo off
for /f "tokens=2 delims=:" %%a in ('ipconfig ^|find "IP Address"') do call :process %%a & goto :next
echo Subnet is %subnet% and host is %host%
set site=Unknown
if %network%==10 set site=SiteA
if %network%==20 set site=SiteB
if %network%==30 set site=SiteC
if %network%==40 set site=SiteD
if %subnet%==192.168.1 set site=SiteE
if %subnet%==128.127.1 set site=Dragon-IT

echo site is %site%

goto :Eof

echo Found %1
for /f "tokens=1-4 delims=." %%a in ("%1") do (set subnet=%%a.%%b.%%c)&(set host=%%d)&(set network=%%c)

Open in new window


VB Script





VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.