• No results found

Introduction to VBScript

N/A
N/A
Protected

Academic year: 2021

Share "Introduction to VBScript"

Copied!
60
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page

Page 11 of of 5959

Introduction to VBScript by

Introduction to VBScript by

Guy ThomasGuy Thomas

September 2005 September 2005

Table of Contents

Table of Contents

Introduction to VBScript

Introduction to VBScript -- Home by Guy ThomasHome by Guy Thomas ... 22 Section 0 Introduction to VBScript

Section 0 Introduction to VBScript ... 33 Section

Section 11 VBScriptVBScript -- Check VersionCheck Version ... 55 Section

Section 22 VBScriptVBScript -- VariablesVariables ... 99 Section

Section 33 Create an OU (Organizational Unit) in Active DirectoryCreate an OU (Organizational Unit) in Active Directory ...1414 Section

Section 44 Create a User in Active DirectoryCreate a User in Active Directory ...2121 Section

Section 55 Map Network DriveMap Network Drive ... 2626 Section

Section 66 Map a Network PrinterMap a Network Printer... 2929 Section

Section 77 Create a Folder (Stage 1 oCreate a Folder (Stage 1 of 3)f 3) ... 3333 Section

Section 88 Create a Text File (Stage 2 of 3)Create a Text File (Stage 2 of 3) ...3737 Section

Section 99 Append Data to Text File (Stage 3 Append Data to Text File (Stage 3 of 3)of 3) ...4141 Section 10

Section 10 Registry ScriptingRegistry Scripting ...4545 Section 11

Section 11 WMI ScriptingWMI Scripting -- MemoryMemory ...5050 Section 12

Section 12 WMI ScriptingWMI Scripting -- Chassis TypeChassis Type ...5454

W

Who is t

ho is this

his Int

Introduction to V

roduction to VBS

BScri

cript eboo

pt ebook aimed at?

k aimed at?

Administrators who need to write simple VBS

Administrators who need to write simple VBScripts.cripts. Techies wishing to automate

Techies wishing to automate repetitive computerrepetitive computer tasks.tasks. Scriptwrite

Scriptwriters who are curious to rs who are curious to know the difference between VBScript andknow the difference between VBScript and JScript.

JScript.

Network Mangers who to more control over

(2)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page

Page 22 of of 5959

Introduction to VBScript

Introduction to VBScript

by Guy Thomas

by Guy Thomas

Simple, yet powerful VBScripts

Simple, yet powerful VBScripts

Introductio

Introduction to

n to VBScript

VBScript

I divided my mission into two strands.  In the first strand, I will show you I divided my mission into two strands.  In the first strand, I will show you thethe range of computing tasks that VBScript can

range of computing tasks that VBScript can automate.automate. While, in the secondWhile, in the second strand I will explain the VBScript commands, methods and

strand I will explain the VBScript commands, methods and syntax.syntax. To fulfilTo fulfil mymy mission, I am going

mission, I am going to provide you with scripts, which have to provide you with scripts, which have a practical purpose,a practical purpose, yet are interspersed with VBScript learning points.

yet are interspersed with VBScript learning points.

Here are the two parallel strands: Here are the two parallel strands:

Tasks for VBScript

Tasks for VBScript

1.

1. Check Version of VBScriptCheck Version of VBScript 2.

2. Variables and HungarianVariables and Hungarian Convention

Convention 3.

3. Active DirectoryActive Directory -- Create OUCreate OU 4.

4. Active DirectoryActive Directory -- CrCreateeate Users

Users 5.

5. Map Network DriveMap Network Drive 6.

6. Map Printer and Set DefaultMap Printer and Set Default Printer

Printer 7.

7. Create a FolderCreate a Folder 8.

8. Create a FileCreate a File 9.

9. Write Text to a FileWrite Text to a File 10.

10. Read and Write to theRead and Write to the Registry

Registry 11.

11. WMIWMI -- MemoryMemory 12.

12. WMIWMI -- Chassis TypeChassis Type

VBSc

VBScript Methods, Commands

ript Methods, Commands

&&

Syntax

Syntax

''Comments (1,10)Comments (1,10)

Error Correcting Code (3,

Error Correcting Code (3, 8,11)8,11) If Then.. Else... End If 

If Then.. Else... End If (3, 8, 11)(3, 8, 11) Input Box (11)

Input Box (11) Loop For...Next

Loop For...Next (2, 12)(2, 12) On Error Resume Next (1) On Error Resume Next (1) Option Explicit (1 Option Explicit (1--12)12) Select Case (12) Select Case (12) Split (10) Split (10) Sub Routine Sub Routine (2)(2) WScript.Echo (1 WScript.Echo (1--12)12) Underscore (_) (1) Underscore (_) (1) Variables

Variables -- Hungarian Convention (2)Hungarian Convention (2) VbCr and vbTab (1)

VbCr and vbTab (1)

Bind to Active Directory Bind to Active Directory GetObject("LD

GetObject("LDAP://RootDSE") AP://RootDSE") (3,4)(3,4) .Create("Orga

.Create("Organizational nizational Unit")Unit") .SetInfo.SetInfo (3)

(3)

CreateObject(

CreateObject("WScript.Netw"WScript.Network") ork") (5,6)(5,6) CreateObject(

CreateObject("WScript.Shell"WScript.Shell") ") (7,10)(7,10) CreateObject(

CreateObject("Scripting.File"Scripting.FileSystemObjecSystemObjec t") (7,8,9)

t") (7,8,9) .CreateFolder

.CreateFolder .CreateTextFile (7).CreateTextFile (7) .OpenTextFile ForAppending (9) .OpenTextFile ForAppending (9) RegRead RegWrite (10) RegRead RegWrite (10) MapNetworkDrive MapNetworkDrive (5)(5) AddPrinterConnec

AddPrinterConnection tion SetDefaultPrinteSetDefaultPrinterr (6)

(6) WMI

(3)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page

Page 22 of of 5959

Introduction to VBScript

Introduction to VBScript

by Guy Thomas

by Guy Thomas

Simple, yet powerful VBScripts

Simple, yet powerful VBScripts

Introductio

Introduction to

n to VBScript

VBScript

I divided my mission into two strands.  In the first strand, I will show you I divided my mission into two strands.  In the first strand, I will show you thethe range of computing tasks that VBScript can

range of computing tasks that VBScript can automate.automate. While, in the secondWhile, in the second strand I will explain the VBScript commands, methods and

strand I will explain the VBScript commands, methods and syntax.syntax. To fulfilTo fulfil mymy mission, I am going

mission, I am going to provide you with scripts, which have to provide you with scripts, which have a practical purpose,a practical purpose, yet are interspersed with VBScript learning points.

yet are interspersed with VBScript learning points.

Here are the two parallel strands: Here are the two parallel strands:

Tasks for VBScript

Tasks for VBScript

1.

1. Check Version of VBScriptCheck Version of VBScript 2.

2. Variables and HungarianVariables and Hungarian Convention

Convention 3.

3. Active DirectoryActive Directory -- Create OUCreate OU 4.

4. Active DirectoryActive Directory -- CrCreateeate Users

Users 5.

5. Map Network DriveMap Network Drive 6.

6. Map Printer and Set DefaultMap Printer and Set Default Printer

Printer 7.

7. Create a FolderCreate a Folder 8.

8. Create a FileCreate a File 9.

9. Write Text to a FileWrite Text to a File 10.

10. Read and Write to theRead and Write to the Registry

Registry 11.

11. WMIWMI -- MemoryMemory 12.

12. WMIWMI -- Chassis TypeChassis Type

VBSc

VBScript Methods, Commands

ript Methods, Commands

&&

Syntax

Syntax

''Comments (1,10)Comments (1,10)

Error Correcting Code (3,

Error Correcting Code (3, 8,11)8,11) If Then.. Else... End If 

If Then.. Else... End If (3, 8, 11)(3, 8, 11) Input Box (11)

Input Box (11) Loop For...Next

Loop For...Next (2, 12)(2, 12) On Error Resume Next (1) On Error Resume Next (1) Option Explicit (1 Option Explicit (1--12)12) Select Case (12) Select Case (12) Split (10) Split (10) Sub Routine Sub Routine (2)(2) WScript.Echo (1 WScript.Echo (1--12)12) Underscore (_) (1) Underscore (_) (1) Variables

Variables -- Hungarian Convention (2)Hungarian Convention (2) VbCr and vbTab (1)

VbCr and vbTab (1)

Bind to Active Directory Bind to Active Directory GetObject("LD

GetObject("LDAP://RootDSE") AP://RootDSE") (3,4)(3,4) .Create("Orga

.Create("Organizational nizational Unit")Unit") .SetInfo.SetInfo (3)

(3)

CreateObject(

CreateObject("WScript.Netw"WScript.Network") ork") (5,6)(5,6) CreateObject(

CreateObject("WScript.Shell"WScript.Shell") ") (7,10)(7,10) CreateObject(

CreateObject("Scripting.File"Scripting.FileSystemObjecSystemObjec t") (7,8,9)

t") (7,8,9) .CreateFolder

.CreateFolder .CreateTextFile (7).CreateTextFile (7) .OpenTextFile ForAppending (9) .OpenTextFile ForAppending (9) RegRead RegWrite (10) RegRead RegWrite (10) MapNetworkDrive MapNetworkDrive (5)(5) AddPrinterConnec

AddPrinterConnection tion SetDefaultPrinteSetDefaultPrinterr (6)

(6) WMI

(4)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page

Page 33 of of 5959 Section

Section00

Introduction to VBScript

Introduction to VBScript

Simple, yet powerful VBScripts Simple, yet powerful VBScripts

Introduction

Introduction

--

What are the Benefits of Learning VBscript?

What are the Benefits of Learning VBscript?

I truly believe that VBScript has

I truly believe that VBScript has a future for automating network administration.a future for automating network administration. The sheer variety of jobs where a

The sheer variety of jobs where a VBscript saves time still amazes me.VBscript saves time still amazes me. ForFor example,

example, toto map network drivemap network drivess or printeror printerss, to, to create users in Active create users in Active Directory,Directory, to

to read and write from files.read and write from files. In addition, there are whole areas of In addition, there are whole areas of computingcomputing which are transformed by scripting, WMI and manipulating the registry spring to which are transformed by scripting, WMI and manipulating the registry spring to mind.

mind.

This ebook will give you

This ebook will give you an appreciation of the range of VBScript objects, foran appreciation of the range of VBScript objects, for example, Active Directory, LDAP, Network, Shell and

example, Active Directory, LDAP, Network, Shell and FileSystemObjeFileSystemObject.ct. We willWe will also manipulate with scripting methods

also manipulate with scripting methods for instance, looping and for instance, looping and if...then...elsif...then...elsee logic.

logic.

Skills (Multi

Skills (Multi

--

Skills)

Skills)

Surprisingly, the principle skills that you need to

Surprisingly, the principle skills that you need to be proficient at VBScript are notbe proficient at VBScript are not mathematical, but logical and

mathematical, but logical and linguistic.linguistic. Attention detail is more important thanAttention detail is more important than genius, especially when you are

genius, especially when you are getting started.getting started. My most enduring advice is keepMy most enduring advice is keep it simple, build your

it simple, build your scripts gradually.scripts gradually. Even though my scripts areEven though my scripts are straightforwar

straightforward, you need no d, you need no conceptual jump to switch from these shortconceptual jump to switch from these short examples to a comprehensive real

examples to a comprehensive real--life script.life script. Can you assemble one table from aCan you assemble one table from a flat

flat--pack?pack? Then you could build a whole office suite, provided you had the time.Then you could build a whole office suite, provided you had the time. It s the same principal with scripting; at the end

It s the same principal with scripting; at the end of this course, you will be of this course, you will be expertexpert at powerful short

at powerful short scripts.scripts. It will then be a short step to assembling a series of It will then be a short step to assembling a series of  simple scripts into a complex production script.

simple scripts into a complex production script.

VBScript is a simple yet powerful language with its

VBScript is a simple yet powerful language with its own rules and syntax.own rules and syntax. InIn VBScript, we have a structured system for creating objects, manipulating their VBScript, we have a structured system for creating objects, manipulating their properties and setting values.

properties and setting values. Because the VBScript language is so efficient, eachBecause the VBScript language is so efficient, each and every word is loaded with meaning.

and every word is loaded with meaning.

My not so

My not so hidden agenda will be to increase your scripting vocabulary.hidden agenda will be to increase your scripting vocabulary. We canWe can begin by looking out for specialist uses of common words such as, loop, split and begin by looking out for specialist uses of common words such as, loop, split and echo.

echo. Let us get into the habit of examining each statement and analyzing theLet us get into the habit of examining each statement and analyzing the significance of every word.

significance of every word. Here are three examples to illustrate what I mean.Here are three examples to illustrate what I mean.

Examples Examples

What is the name of the object created here?

What is the name of the object created here? Set objShell =Set objShell = CreateObject("WScript.Shell")

CreateObject("WScript.Shell") (Ans: objShell)(Ans: objShell) What

What is the property of objShell called?is the property of objShell called? objShell.SendKeobjShell.SendKeys "Hello ys "Hello Guy"Guy" (Ans:(Ans: .SendKeys)

.SendKeys)

How could we change the value from "Hello Guy" to say "Goodbye"? How could we change the value from "Hello Guy" to say "Goodbye"? objShell.SendKe

objShell.SendKeys "Hello ys "Hello Guy"Guy" (Ans:

(5)

Introduction to VBScript.doc By Guy Thomas

Page 4 of 59

One revelation from my post-bag, which constantly amazes me, is the different ways that people write scripts. Another surprise is that each person thinks that their way is the only way to write code. Naturally as your mentor, I will give you ideas, but please distil my advice and devise methods which suit you. Here are a few secrets learnt at the bitter school of hard knocks.

Secrets of Scripting

Develop a naming convention for all your scripts. Save your scripts in a special folder.

Don't be afraid to create lots of versions of test scripts. Many is the time that I end up with a script that does not work and I cannot find out why. The speediest solution is to revert to a version that I saved earlier which did work.

Make liberal use of comments, especially at the top of the script. Six months later, you will forget why made the script.

When scripting Active Directory, create a test OU, a test user. Always remember that Scripting mimics task that you can carryout manually with Explorer, Active Directory Users and Computers or even Regedit.

Get a good scripting editor at the outset, for Example OnScript.

This page covered the following VBScript ideas.

My theme of this ebook is that VBScript provides variety of opportunities to automate network tasks. To be successful at VBScript while you need to be

multi-skilled, a logical and methodical mind is more important than mathematical skill.

(6)

Introduction to VBScript.doc By Guy Thomas

Page 5 of 59

Section1

VBScript

-

Check Version

Which Version of VBScript are you using?

Introduction to Checking Version Numbers

I want to begin with the relatively easy task of checking your VBScript version numbers. For this first script, I want to concentrate on the pure VBScript commands, methods and syntax. For example,

WScript.Echo, .Version, underscore (_) and vbCr.

There are occasions when you need to investigate the VBScript version number. For example, if you have old clients with version 2, some VBScript commands may not work. To give a specific example, you may want a script to pause, in which case you could use WScript.Sleep. The problem is that this, .Sleep property was only added in WSH version 5.1. In fact, we are faced with a

paradox, modern XP machines, which don t really need to pause, obey the .Sleep command, whereas Windows 9x machines, which need .Sleep, cannot interpret this command. Thus, our task is to build a very simple script that checks the version of VBScript.

The first bonus of checking version numbers is that our investigation reveals just how many components are involved in a VBscript, for instance, Windows Scripting Host (WSH) and also VBScript itself.

Topics for Checking Version Numbers

Example 1 - VBScript to Check the WSH Version

Example 2 - VBScript to Check the WSH Version and Build Number Example 3 - VBScript to Check the VBScript Version

Summary of Checking Version Numbers

Example 1

-

VBScript to Check the WSH Version

VBScripts need a shell called WSH (Windows Scripting Host). I visualise the WSH shell as a room where the script engine performs its instructions. My point is that if there is no WSH room , then VBScript cannot process our instructions.

Examples 1 and 2 are designed to extract the version information about WSH and 'echo' the information to your screen. (In Example 3 we switch to the VBScript executable itself.)

Prerequisites

This is a script that will execute equally well on a Windows server or an XP machine.

Instructions for Checking WSH Version

1. Copy and paste the example script below into notepad or a VBScript editor. 2. Save the file with a .vbs extension, for example, WSH.vbs

(7)

Introduction to VBScript.doc By Guy Thomas

Page 6 of 59

Sample VBScript to Check the WSH Version

' WSH.vbs

' Sample VBScript to check WSH Version

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.3 - September 2005

' ---On Error Resume Next

WScript.Echo "WSH Version: " & WScript.Version WScript.Quit

Learning Points

Note 1: WScript.Echo calls for a WSH message box. The next command "WSH Version: " & WScript.Version, tell the script engine what to put in that box. I am expecting the script to return a WSH message box displaying - WSH Version: 5.6. See screen shot opposite.

WScript.Echo may seem trivial, as it does not actually do any useful work, however, WScript.Echo is worth mastering, as it is probably the number one technique in troubleshooting VBScript. Incidentally, this command is not case sensitive.  (Wscript.echo is equally as effective.)

Note 2: Observe that we have a mixture of literals - "WSH Version: " and

variables - WScript.Version. Paying attention to detail pays off. In this instance, notice how the space before the closing quotes makes the output easier to

understand.

Note 3: Time and time again ampersand (&) is your friend for joining VBScript components. I have to confess that I am often concentrating so hard on the more difficult commands that I forget the ampersand. When I make this sin of  omission, WSH brings me up sharply with a message: Code 800A0401 - Expected end of statement.

Note 4: 'On Error Resume Next' is not strictly necessary in this script. This is the basic troubleshooting command that says, if there is a problem, carryon and do your best. In other scripts, On Error Resume Next salvages useful commands after a mistake, moreover, it suppresses the WSH error message box.

Note 5: I almost forgot to mention ' Comments. A single quote tells VBScript to disregard what follows the single quote. The first five lines of this script are

remmed out using this technique. The idea is to add explanations of what the script is designed to achieve. With a long script, I like to add comments between each section.

(8)

Introduction to VBScript.doc By Guy Thomas

Page 7 of 59

Example 2

-

VBScript to Check the WSH Version and Build Number

Script to Display WSH and File Information

WSHname.vbs

' Sample VBScript to check WSH Version

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.3 - September 2005

' ---On Error Resume Next

WScript.Echo "WSH Version: " & WScript.Version & " " & WScript.BuildVersion _ & vbcr & "File name: " & WScript.ScriptName

WScript.Quit

Learning Points

Note 1: Most of the time, I only use WScript.Echo and perhaps WScript.Quit, I was surprised to discover that WScript has so many other properties, for example .Version, .BuildVersion and even .ScriptName. From a teaching perspective, the message is that objects have properties, which we access with the syntax

object.dot.property. Incidentally, my WScript build number was 8827.

Note 2: One potential problem with VBScript commands is that they run to more than 80 characters. Moreover, VBScript has no concept of word-wrap, so if you just continue the same instruction on the next line, VBScript will interpret your intention as two instructions and not one. Fortunately, there is a solution, the underscore (_). What underscore does is tell VBScript that the command has not yet finished, but to read the second half of the same command on the next line.

If you are familiar with other scripting languages then you could looking upon the (_) is as an escape character for the carriage return.

Note 3: Observe the command vbcr, this makes a carriage return in the actual output message box. It is purely cosmetic, but it often makes output easier to understand. Take the time to be sure of the difference between (_) and vbCr. For instance, remove the (& vbCr) and the script will still run. However, remove the (_) and it will not work.

Example 3

-

VBScript to Check the VBScript Version

As we will see, our scripts require both VBScript itself and also a WSH shell. This script concentrates on the version number of the VBScript executable.

Incidentally, you can confirm the information by checking the information directly on cscript.exe and wscript.exe in the Windows\ System32 folder.

Please note that this script checks VBScript and is different from Example 1 and 2 which report version numbers for WSH. Specifically, check how the commands ScriptEngineMajorVersion and ScriptEngineMinorVersion replace WScript.Version.

(9)

Introduction to VBScript.doc By Guy Thomas

Page 8 of 59

Sample Script to Check the VBScript Version

' VBScript.vbs

' Sample Script to check VBScript Version

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.1 - September 2005

' ---WScript.Echo "VBScript Version: " & ScriptEngineMajorVersion _ & "." & ScriptEngineMinorVersion

WScript.Quit

Learning Points

Note 1: Unlike example 1 this script needs to build the version number from two numbers, and artificially

concatenate a dot (".") in between the two parts of the version number.

Challenge:

These three scripts are so short that you could easily bolt them together. This would mimic real life situations where you build scripts in stages, get them working and then bolt them together to create the production script.

Summary of Checking Version Numbers

From a practical point of view, it may be necessary to check the version of  VBScript or WSH. From a pure scripting point of view, there are parallels with English. When composing ordinary English, many of us - me included, are unsure when to use a semi-colon; a dash is even harder to master. Syntax is equally important in VBScript, therefore take a minute or two to master the underscore (_) and vbcr.

This page covered the following VBScript methods, commands and syntax:

(10)

Introduction to VBScript.doc By Guy Thomas

Page 9 of 59

Section2

VBScript

-

Variables

Variables are a vital scripting tool

Introduction

to VBScript Variables

On this page I am going to take two learning themes and weave them together. One theme is represented by VBScript variables and the other theme is creating a computer account.

Later on this page, we will discuss the advantages of using the Hungarian

Convention for naming variables, but first, let us review what the term variable means in the context of VBScript. One obvious definition of a variable is the opposite of a constant. Constants remain at their initial value, whereas variables can change their values during the course of a script, for example, processing a different account each time the script goes through a loop. Think of variables as placeholders for items that will change during the course of a script.

In this ebook, we will create three types of Active Directory Objects,

.Create("Computer..."), .Create("Organizational Unit..."), and .Create("user..."). This page features the .Create("Computer..") method, once you have mastered the VBScript technique for a computer, then you can apply it to different

situations, for example, create an OU (Section 3) or create a User (Section 4). Even if you don't have Active Directory, you can still study the VBScript methods, for example, GetObject("LDAP://rootDSE"), .SetInfo and .Put.

Topics for Variables

What is a VBScript Variable?

Example 1 - Using a String Variable

Example 2 - Using a Variable to Increment a Loop The Hungarian Variable Convention

Summary of VBScript Variables

What is a VBScript Variable?

The discipline of declaring variables gives me control over VBScript. Variables help me plan and best of all, variables help me when it comes to troubleshooting scripts. I use variables in two ways, firstly, suppose I want to repeat the name of  one computer again and again throughout the script. What I do is assign a name to a variable at the start of the script, thereafter I use the variable when I want to refer to the name. For example strXP = "XPMachine". The payback for what may seem like extra work, is when I want the script to work with a different value, say strXP = "VistaMachine". I only have to change the value in one place, moreover, I know that place will be near the top of my script.

My second job for variables is as placeholders in loops. Incidentally, loops never cease to amaze me for their power to automate repetitive tasks. Let us imagine that I have a VBScript routine, which creates a Computer, imagine also that I have a list of 100 machine names in a file. Loop + variable + incrementor = lots of new Computer accounts. To keep it simple, on this page the scripts do not read from a file, instead each loop appends a different number to the base name, XPMachine1, XPMachine2 etc..

(11)

Introduction to VBScript.doc By Guy Thomas

Page 10 of 59

Example 1

-

Using a String Variable

In this first Example, observe how VBScript employs the variable strXP to build the new computer object. See how I set strXP = "XPMachine. Then look again and see how many more times strXP appears in the script. Now see how easy it would be to change strXP to = "VistaMachine", compared with the hassle of  changing each of the two, or is it three, further occurrences of the corresponding computer name.

Prerequisites

While I designed this script purely to demonstrate variables, there is no reason why you should not create and test the following VBScript provided you are connected to an Active Directory Domain.

Instructions

1. Copy and paste the script below into notepad.

2. Save the file with .vbs extension e.g. ComputerSimple.vbs 3. Double click and then check the message box

4. You may like to launch Active Directory Users and Computers and check the Computers container for new Computer accounts. Press F5, or refresh as necessary.

' ComputerSimple.vbs

' Sample VBScript to create a Computer (Simple)

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.2 - September 2005

' ---Option Explicit

Dim strXP, objRootDSE, objContainer, objComputer strXP = "XPMachine"

Set objRootDSE = GetObject("LDAP://rootDSE")

Set objContainer = GetObject("LDAP://cn=Computers," & _ objRootDSE.Get("defaultNamingContext"))

Set objComputer = objContainer.Create("Computer", "cn=" & strXP) objComputer.Put "sAMAccountName", strXP & "$"

objComputer.Put "userAccountControl", 4096 objComputer.SetInfo

WScript.Echo "Created a new computer called " & strXP WScript.Quit

Learning Points

Note 1: For now, trust me, just concentrate on the variable strXP and do not worry about how the script binds to Active Directory. (We will cover Active Directory components in section 3.)

Note 2: By declaring and using variables in your VBScripts, you can manipulate their values later in the script. Trace all the occurrences of strXP in the above example.

(12)

Introduction to VBScript.doc By Guy Thomas

Page 11 of 59

Example 2

-

Using a Variable to Increment a Loop.

Loop counters are another classic application for variables. See how the script creates 10 computers and puts them all in same OU. The variable

intComputerNum is a vital cog in enabling the script loop ten times. The result is an efficient script, which builds computers accounts. Thanks to the variable

intComputerNum, the machines have unique names, XPMachine1 to XPMachine10.

' ComputerLots.vbs

' Sample VBScript to create 10 Computers

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.3 - September 2005

' ---Option Explicit

Dim strXP, objRootDSE, objContainer, objComputer Dim intComputerNum, objNew

strXP = "XPMachine"

Set objRootDSE = GetObject("LDAP://rootDSE")

Set objContainer = GetObject("LDAP://cn=Computers," & _ objRootDSE.Get("defaultNamingContext"))

For intComputerNum = 1 To 10 objNew = strXP & intComputerNum

Set objComputer = objContainer.Create("Computer", "cn=" & objNew) objComputer.Put "sAMAccountName", objNew & "$"

objComputer.Put "userAccountControl", 4096 objComputer.SetInfo

Next

intComputerNum = intComputerNum -1

WScript.Echo intComputerNum & " new computers created "

Note 1: In Example 2 (above), I would like to isolate the For... Next loop and concentrate on the role of the variable intComputerNum. So often, the real reason why you are creating a script is to automate a repetitive task. That

means getting the basic task correct, (Example 1) and then 'topping and tailing' the script with a For ... Next loop. (Example 2).

Note 2: The command: For intComputerNum = 1 To 10 controls how many loops, how many computers to create. While I used a long variable name intComputerNum, many scriptwriters would have used, For i = 1 to 10. The reason that I choose a long name is because 'i' is such a short variable name, if  you blink, you miss the fact that the command is using a variable.

Note 3: From an Active Directory perspective, this script demonstrates that you need to create a sAMAccountName for a computer object. It also shows that the default UserAccountControl value for a computer is 4096 and not 512. I say again, we will feature the Active Directory commands in later scripts (page 3).

(13)

Introduction to VBScript.doc By Guy Thomas

Page 12 of 59

The Hungarian Variable Convention

The idea behind the Hungarian naming Convention is to give variables consistent and meaningful names, especially with the prefix part of the variables. VBScript allows to you declare variables beginning with any reasonable alphanumeric

character.  The Hungarian Convention says, 'Wouldn't it be a good idea to always begin string variables with s (or str) and integers with i (or int)'. At a stroke, the prefix gives you an extra clue about the purpose of the variable. For example, strContainer expects a string value such as "XPMachine"; whereas a variable called intCounter, intimates that the values will be whole numbers.

VBScript does not insist upon the Hungarian Convention. On the one hand, I wish VBScript would enforce strict naming; on the other hand it allows you, or I, to develop our own dialect of the Hungarian Convention. One of the stricter dialects of the Hungarian Convention uses mainly single letter prefixes, for example, s for string, o for object, i for integer.

My message is this, devise your own dialect of the Hungarian Convention and stick to it. If you would like to research the Hungarian Convention, look for the names Charles Simonyi, who invented the convention and Charles Petzold who adapted it to Windows scripting. To summarise, naming variables consistently is important, the Hungarian Convention is a worthy concept. Incidentally, other scripting languages enforce the convention more rigorously than VBScript.

Here is a system that I try to adhere to:

int - Integer. Example intComputerNum representing 10 or 50 str - String. Example strOU or strDomain

obj - Object. Example objUser or objComputer

There are other less common variable prefixes, for instance: err error, dtm -date, boo - Boolean. Are variables case sensitive? The answer is no. For instance, strXP would be the same as StrXP or strXp. That does not mean that you should change capitalization from one instance to the next. Get into good habits; they will reward you when it comes to dealing with Active Directory properties which are case sensitive.

(14)

Introduction to VBScript.doc By Guy Thomas

Page 13 of 59

Hungarian Convention Example:

Let us revisit Example 2, and identify my version of the Hungarian Convention, for example, the variables strXP objNew and intComputerNum.

' ComputerLots.vbs

' Sample VBScript to create 10 Computers

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.4 - September 2005

' ---Option Explicit

Dim objNew, objRootDSE, objContainer, objComputer Dim intComputerNum, strXP

strXP = "XPMachine"

Set objRootDSE = GetObject("LDAP://rootDSE")

Set objContainer = GetObject("LDAP://cn=Computers," & _ objRootDSE.Get("defaultNamingContext"))

For intComputerNum = 1 To 3

objNew = strXP & intComputerNum

Set objComputer = objContainer.Create("Computer", "cn=" & objNew) objComputer.Put "sAMAccountName", objNew & "$"

objComputer.Put "userAccountControl", 4096 objComputer.SetInfo

Next

intComputerNum = intComputerNum -1

WScript.Echo intComputerNum & " new computers created "

Learning Points

Note 1: VBScript is an object based language, therefore I prefix the names of  my Container and Computer objects with obj, e.g. objComputer.

Note 2: when I need a numeric variable, I prefix it with int e.g.

intComputerNum, other writers would use iComputerNumber. Incidentally, it constantly surprises me that VBScript relies on pure logic more than pure maths.

Note 3: When it comes to values, many of my variables rely on names, so I prefix them with str, short for 'string variable' e.g. strXP.

Summary of VBScript Variables

Choose meaningful names for your variable, select a word or words that describe the purpose of the variable. Best practices suggests the length should be about 8 - 16 characters. strXP gives you a clue that this could be an XP name, while objComputer is fairly self -evident.

This page covered the following VBScript methods, commands and syntax:

String Variables, Number Variables, Object Variables, also For .... Next (Loop) and .Create("Computer...")

(15)

Introduction to VBScript.doc By Guy Thomas

Page 14 of 59

Section3

Create an OU (Organizational Unit) in Active

Directory

Build your container object

Tutorial for Creating an OU (Organizational Unit) with VBScript

This script builds on the knowledge of variables covered in section 2. It also extends the .Create("Computer...") method to .Create("Organizational Unit..."). As promised in section 2, here is where we concentrate on Active Directory techniques such as binding the RootDSE namespace.

When I visit companies, it surprises me that only 50% of network managers create any OUs in their Active Directory. The rest keep all their

accounts in the Users (or Computers) container. The distinction between OUs and container objects is not just a matter of a strange book symbol on the OU, see Accounts OU on diagram opposite. OUs are great for not only organizing your user accounts, but also OUs make it easier to fine-tune your group

policies. (You cannot create or assign Group Policies to the Users or Computers containers.)

When you start scripting Active Directory objects it is important to distinguish between an OU and a Container object. It is easy to make a mistake and try to write, CN=Accounts, or OU=Computers, when it should be OU=Accounts and CN=Computers. (See diagram above.)

Topics for Creating an OU (Organizational Unit) with VBScript

Our Mission and Goal

Example 1 - Create a Top Level OU Example 2 - Create a Child OU

Example 3 - Adding error-correcting Code Summary for Creating User Accounts

Our Mission and Goal

Unlike the FileSystemObject, or Network scripts, this mission requires access to an Active Directory domain. While we create OUs (Organizational Units) primarily as containers to organize users, let us take the opportunity and learn about

scripting commands such as: 'Set, Create(Object), Get(Object) and .SetInfo'.

The subsidiary reason for studying OUs is preparing for that day when you need to alter objects in that OU with a VBScript. There are traps for the unwary; for example, you need to ensure that your script binds, not to the Users container, but binds to a named OU.

Example 1

-

Create a Top Level OU

Please would you inspect Active Directory Users and Computers and confirm that there is no tiny book symbol on your Users folder. My point is that Users is a container object, referenced by CN=Users and not an OU referred to by: OU=Users.

(16)

Introduction to VBScript.doc By Guy Thomas

Page 15 of 59

(17)

Introduction to VBScript.doc By Guy Thomas

Page 16 of 59 Instructions

1. Important: Which OU will create? My script uses OU=Accounts to

generate an Organizational Unit called accounts. If you prefer a different OU name, then change line 10 in your script.

2. Copy and paste the script below into notepad.

3. Save the file with .vbs extension e.g. Accounts.vbs. 4. Double click and examine the message boxes.

5. Open Up your Active Directory Users and Computers and inspect the OUs.

' Account.vbs

' VBscript to create an OU (Organizational Unit) ' Note two steps to set domain

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.3 - September 2005

' ---' Option Explicit

Dim objRoot, objDomain, objOU Dim strContainer

strContainer ="OU=Accounts"

' Section to bind to YOUR Active Directory. Set objRoot = GetObject("LDAP://rootDSE")

objDomain = objRoot.Get("defaultNamingContext") Set objDomain = GetObject("LDAP://" & objDomain) ' Section to create the OU defined by strContainer ' Also note the use of: .SetInfo

'On Error Resume next

Set objOU = objDomain.Create("organizationalUnit", strContainer) objOU.SetInfo

WScript.Echo "New Top Level OU created = " & strContainer WSCript.Quit

Learning Points

-

Binding to Active Directory

Building on my theme of mastering VBScript commands, I would like to draw your attention to the following section of the Example 1 script.

' Section to bind to YOUR Active Directory. Set objRoot = GetObject("LDAP://rootDSE")

objDomain = objRoot.Get("defaultNamingContext") Set objDomain = GetObject("LDAP://" & objDomain)

(18)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page 17 of 59 Page 17 of 59 Note 1:

Note 1: GetObject() retrieves data.GetObject() retrieves data. Later, in the full script we will make a newLater, in the full script we will make a new OU with the

OU with the sister command CreateObject().sister command CreateObject().

Note 2:

Note 2: The 'Set' Command means that the The 'Set' Command means that the variable called objRoot points to thevariable called objRoot points to the base of the LDAP name

base of the LDAP name space.space. Think of rootDSE as tunnelling down into theThink of rootDSE as tunnelling down into the heart of Active Directory and then

heart of Active Directory and then returning with information.returning with information. In this instance,In this instance, naming information.

naming information.

Note 3:

Note 3: DefaultNamingConteDefaultNamingContext is a xt is a wonderful command because it removes mywonderful command because it removes my need to know your domain.

need to know your domain. Without this technique, we would have to Without this technique, we would have to hard codehard code the domain name.

the domain name. Thanks to Thanks to DefaultNamingConteDefaultNamingContext, the script xt, the script retrieves theretrieves the distinguished name automatically, in my case it would

distinguished name automatically, in my case it would be: dc=cp, dc=mosel. (DCbe: dc=cp, dc=mosel. (DC = Domain Context, not

= Domain Context, not Domain Controller).Domain Controller). While, I do not know the name of While, I do not know the name of  your domain, when the script runs on your machine it automatically extracts the your domain, when the script runs on your machine it automatically extracts the name of your domain.

name of your domain. Clever.Clever.

Note 4:

Note 4: You may see other people's scripts, which Set ObjDomain with one You may see other people's scripts, which Set ObjDomain with one lineline iinstead of two.nstead of two. I admit that it is possible to write tighter code, but my way helpsI admit that it is possible to write tighter code, but my way helps us to breakdown the stages of

us to breakdown the stages of binding to Active Directory.binding to Active Directory. As you will see, I amAs you will see, I am keen on scripts which employ the

keen on scripts which employ the 'salami' technique to slice a task into'salami' technique to slice a task into manageable stages

manageable stages..

Learning Points

Learning Points

--

Creating the actual OU

Creating the actual OU

Here is the section which creates and then

Here is the section which creates and then saves the new OU.saves the new OU.

strContainer ="OU=Accounts" strContainer ="OU=Accounts" 'On Error Resume next

'On Error Resume next Set objOU =

Set objOU = objDomain.Create("organizatobjDomain.Create("organizationalUnit", strContainer)ionalUnit", strContainer) objOU.SetInfo

objOU.SetInfo

Note 1:

Note 1: Guy loves variables, so here is the Guy loves variables, so here is the name of the variable which holds name of the variable which holds thethe OU name:

OU name:

strContainer ="OU=Accounts" strContainer ="OU=Accounts"

Note 2:

Note 2: Observe the use of the 'Set' Observe the use of the 'Set' command, as in Set objOU.command, as in Set objOU.

Note 3:

Note 3: What the script is saying is What the script is saying is this, start with the domain this, start with the domain (objDomain),(objDomain), now create a new OU (Not a user or a computer).

now create a new OU (Not a user or a computer). Next, the script extracts theNext, the script extracts the name of the new OU from the strContainer

name of the new OU from the strContainer variable.variable.

Note 4:

Note 4: Another member of the Set family Another member of the Set family is .SetInfo.is .SetInfo. Take special note of Take special note of  .SetInfo because overlooking this command can mean that the

.SetInfo because overlooking this command can mean that the script runsscript runs silently, without error, but

silently, without error, but unfortunately, nothing actually gets created!unfortunately, nothing actually gets created! OmittingOmitting .SetInfo is rather like filling in the dialog boxes, but forgetting to click the OK .SetInfo is rather like filling in the dialog boxes, but forgetting to click the OK button.

(19)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page 18 of 59 Page 18 of 59

Example 2

Example 2

--

Create a Child OU

Create a Child OU

The idea of this VBScript example is to create a child OU.

The idea of this VBScript example is to create a child OU. My assumption is thatMy assumption is that you have already made a parent or

you have already made a parent or top level OU as top level OU as describedescribed in Example 1.d in Example 1.

Creating a child OU is

Creating a child OU is simple but there is a simple but there is a classic trap.classic trap. Which of these twoWhich of these two sequences should you use?

sequences should you use?

strContainer

strContainer = parent, chil= parent, child.d. or strContainer = child, parent? or strContainer = child, parent?

Answer: strContainer = child, parent Answer: strContainer = child, parent

Assuming that the parent is called Accounts, here is

Assuming that the parent is called Accounts, here is a real example:a real example: strContainer

strContainer ="OU=Child,OU=="OU=Child,OU=Accounts".Accounts". See diagram opposite.See diagram opposite.

Some people find this sequence counter intuitive, others, try both

Some people find this sequence counter intuitive, others, try both ways and seeways and see which works.

which works. The gifted deduce the sequence from The gifted deduce the sequence from first principles.first principles. If you had toIf you had to add the user name, then the

add the user name, then the full DN (distinguished name) would be:full DN (distinguished name) would be: cn=guyt,OU=Child

cn=guyt,OU=Child,OU=Accounts,d,OU=Accounts,dc=cp,dc=cc=cp,dc=com.om. When you see the full path, theWhen you see the full path, the sequence "OU=Child,OU=Accounts", becomes obvious.

sequence "OU=Child,OU=Accounts", becomes obvious.

Tip: When scripting OUs, pay particular attention to the

Tip: When scripting OUs, pay particular attention to the placement of commas.placement of commas. To create a child OU we just need one comma in the string variable.

To create a child OU we just need one comma in the string variable. (In other(In other cases, but not here, we need two

cases, but not here, we need two commas.)commas.)

' VBscript to create a

' VBscript to create a child OU (Organizational Unit)child OU (Organizational Unit) ' Author Guy

' Author Guy Thomas http://computerperformancThomas http://computerperformance.co.uk/e.co.uk/ ' Version 2.3

' Version 2.3 - September 2005- September 2005 '

' ---'---' Option Explicit

Option Explicit

Dim objRoot, objDomain, objOU Dim objRoot, objDomain, objOU Dim strC

Dim strContainerontainer err.number = vbEmpty err.number = vbEmpty ' Section to create the OU

' Section to create the OU defined by strContainerdefined by strContainer strContainer

strContainer ="OU=Child,OU=Acc="OU=Child,OU=Accounts"ounts" ' Section to bind to YOUR Active Directory. ' Section to bind to YOUR Active Directory. Set objRoot =

Set objRoot = GetObject("LDAP://rootGetObject("LDAP://rootDSE")DSE") objDomain =

objDomain = objRoot.Get("defaultobjRoot.Get("defaultNamingContext")NamingContext") Set objDomain = GetObject("LDAP://" &

Set objDomain = GetObject("LDAP://" & objDomain)objDomain) On Error Resume next

On Error Resume next

Set objOU = objDomain.Create("organizationalUnit", strContainer ) Set objOU = objDomain.Create("organizationalUnit", strContainer ) objOU.Put "Description", "Guy's OU"

objOU.Put "Description", "Guy's OU" objOU.SetInfo

objOU.SetInfo

' Confirmation Message ' Confirmation Message

If Err.Number = vbEmpty Then If Err.Number = vbEmpty Then

WScript.Echo "New Child OU created = " &

WScript.Echo "New Child OU created = " & strContainerstrContainer Else

Else

WScript.Echo "Problem: " & err.number WScript.Echo "Problem: " & err.number End If 

End If  WScript.Quit WScript.Quit

(20)

Introduction to VBScript.doc

Introduction to VBScript.doc By Guy ThomasBy Guy Thomas

Page 19 of 59 Page 19 of 59

Learning Points

Learning Points

--

Creating the Child OU

Creating the Child OU

Note 1:

Note 1: The key way to The key way to control this script is through the control this script is through the strContainer variable.strContainer variable. To create the child OU I amend:

To create the child OU I amend: strContainer

strContainer ="OU=Child,OU="OU=Child,OU=Accounts"=Accounts"

Note 2:

Note 2: With Err.Number, I have With Err.Number, I have added primitive erroradded primitive error--correcting code incorrecting code in preparation for Example 3.

preparation for Example 3.

Example 3

Example 3

--

Adding error

Adding error

--

correcting Code

correcting Code

As with every

As with every--day life, I always like to anticipate what could go wrong in myday life, I always like to anticipate what could go wrong in my scripts.

scripts. Specifically, I want the script to handle two Specifically, I want the script to handle two situations:situations: 1) Where the child OU already exists

1) Where the child OU already exists

2) The situation where there is no Parent OU 2) The situation where there is no Parent OU

To handle the errors, I

To handle the errors, I divided the OU path into strParent and strContainer.divided the OU path into strParent and strContainer. MostMost of the error

of the error--correcting takes place in the correcting takes place in the subroutine called GuyError().subroutine called GuyError().

' VBscript to create a

' VBscript to create a child OU (Organizational Unit)child OU (Organizational Unit) ' With error

' With error--correcting codecorrecting code ' Author Guy

' Author Guy Thomas http://computerperformancThomas http://computerperformance.co.uk/e.co.uk/ ' Version 2.4

' Version 2.4 - September 2005- September 2005 '

' ---'---' Option Explicit

Option Explicit

Dim objRoot, objDomain, objOU Dim objRoot, objDomain, objOU Dim strContainer, strParent Dim strContainer, strParent err.number = vbEmpty err.number = vbEmpty

' Section to bind to YOUR Active Directory. ' Section to bind to YOUR Active Directory. Set objRoot =

Set objRoot = GetObject("LDAP://rootGetObject("LDAP://rootDSE")DSE") objDomain =

objDomain = objRoot.Get("dobjRoot.Get("defauefaultNamingContext")ltNamingContext") Set objDomain = GetObject("LDAP://" &

Set objDomain = GetObject("LDAP://" & objDomain)objDomain) ' Section to create the OU

' Section to create the OU defined by strContainerdefined by strContainer strParent ="OU=Accounts"

strParent ="OU=Accounts"

strContainer ="OU=Child," & strParent strContainer ="OU=Child," & strParent On Error Resume next

On Error Resume next Set objOU

Set objOU = objDomain.Create("organizationalUnit",= objDomain.Create("organizationalUnit", strContainer )strContainer ) objOU.Put "Description", "Guy's OU"

objOU.Put "Description", "Guy's OU" objOU.SetInfo

objOU.SetInfo ' error

' error--correcting Codecorrecting Code

If Err.Number <> vbEmpty Then If Err.Number <> vbEmpty Then

Call GuyError Call GuyError Else

Else

WScript.Echo "New Child OU created = " &

WScript.Echo "New Child OU created = " & strContainerstrContainer End If 

End If 

WScript.Quit(0) WScript.Quit(0) ' error

' error--correcting code to create Parent OUcorrecting code to create Parent OU Sub GuyError()

Sub GuyError() If Err.number = "

If Err.number = "--2147019886" then2147019886" then Wscript.Echo "Child OU already created" Wscript.Echo "Child OU already created" WScript.Quit(1)

WScript.Quit(1) Else

Else

Wscript.Echo "Error " & Err.number Wscript.Echo "Error " & Err.number

Set objOU = objDomain.Create("organizationalUnit", strParent ) Set objOU = objDomain.Create("organizationalUnit", strParent ) objOU.Put "Description", "Guy's Bulk Users OU"

objOU.Put "Description", "Guy's Bulk Users OU" objOU.SetInfo

objOU.SetInfo

Set objOU = objDomain.Create("organizationalUnit", strContainer ) Set objOU = objDomain.Create("organizationalUnit", strContainer ) objOU.SetInfo

objOU.SetInfo

WScript.Echo strParent & " Child and Parent OU Created " WScript.Echo strParent & " Child and Parent OU Created " End If 

End If  End Sub End Sub

(21)

Introduction to VBScript.doc By Guy Thomas

Page 20 of 59

Note 1: Firstly, I researched the specific err.number for the situation where the OU already existed, the answer turned out to be -2147019886. In the WSH Message box you actually see, Error: 80071392. (To check the math launch Calc.exe in Scientific Calculator mode. Now compare 80071392 Hex with 2147019886 decimal)

Note 2: All scripting languages have sub-routine functions, I challenge you to trace how 'sub GuyError()' makes use of strParent and strContainer.

Summary Creating an OU

It is surprising how often you need an OU. For example, testing Group Policies or testing Logon Scripts. There again, perhaps you just want to organize your

accounts in Active Directory Users and Computers. It's worth remembering that while I call it OU, Microsoft give the object its full name Organizational Unit.

My script will build your Active Directory Organizational Unit. All you need to do is adjust the variable:

strContainer = "OU = Accounts". If you have the time, then go through the script searching for all the script commands. Should there be any methods or verbs that you do not understand, do refer to the learning points.

This page covered the following VBScript methods, commands and syntax:

.Create(organizationalUnit", If...then... else...End If, Child and Parent OUs, sub GuyError(), err.number

(22)

Introduction to VBScript.doc By Guy Thomas

Page 21 of 59

Section4

Create a User in Active Directory

Bind to Active Directory

Introduction to Create a User in Active Directory

Creating Active Directory objects is a fertile area for VBScript. My suggestion, or even challenge is to search for common ground in all Active Directory type of  scripts. For example, each Active Directory script 'binds' to the root of the

domain name space. Invariably, Guy's scripts employ a strContainer variable to control the OU where the new object will be born. Production scripts also need a loop. After all the reason that we are scripting rather than performing the same task manually is to save time with routines that automate.

Tutorial for Creating a User Account with VBScript

This page has VBScript examples to show you how to create User accounts in your domain. I urge you to take on board my advice to build your scripts in stages. The benefit of creating scripts in small sections is that not only do you understand each part, but also your brain will see ways of applying a section in a different scenario. For example, once you learn how to bind with Active Directory to create a User object, it's easy to modify the script and create a Contact object instead.

Topics for Creating a User Account with VBScript

Our Mission and Goal

Example 1: Script to Create a User in Active Directory VBScript Tutorial - Learning Points

Example 2: Script to Create a User in a Named OU Summary for Creating User Accounts

Our Mission and Goal

Our first goal is to create a User account in Active Directory's Users container. A more realistic mission is to create users in a named OU, and we will tackle that goal in Example 2.

Breaking down the task of creating a user

Whilst our mission is to create a user in an OU, the teaching progression is to create one user in the default Users container, then modify the script to deliver the account to an OU, which we control with strContainer.

Declare the variables. Bind to active directory. Add the sAMAccountName.

Additional tasks not covered here.

Enable the account.

Add other properties, for example sn, office. Add a loop to create multiple users.

(23)

Introduction to VBScript.doc By Guy Thomas

Page 22 of 59

Example 1

-

Script to Create a User in Active Directory

In this script, we concentrate on the essential VBscript commands necessary to build a User account in Active Directory Users and Computers. For example, GetObject("LDAP://rootDSE") and .Create("User"). Even though I am

experienced at creating VBScripts, I still run manually through creating the object in Active Directory Users and Computers. What I find is the GUI's menus, actions and dialog boxes help me to rehearse the corresponding stages in my script.

Prerequisites

I recommend that you logon at a domain controller. If you are a long way from the server, Remote Desktop would be a suitable alternative. If that is not

possible, you could get these scripts to work from an XP machine as a non-administrator. However, why introduce extra complications? Especially at the beginning, you want easy success, with fewest obstacles.

Instructions for Creating a User Account in Active Directory

1. You should run this VBScript on a Windows Active Directory domain. 2. Copy and paste the example script below into notepad or a VBScript

editor.

3. Decide whether to change the value for strUser. DomGuy2 is not a particularly attractive name.

4. Save the file with a .vbs extension, for example: Users .vbs.

5. Double click Users .vbs and check the Users container for strUser.

Script to Create a User in a Named OU (Organizational Unit)

' Users .vbs

' Sample VBScript to create a User in Users .

' Author Guy Thomas http://Computerperformance.co.uk/ ' Version 1.3 - May 2005

' ---' Option Explicit

Dim strUser

Dim objRootLDAP, objContainer, objNewUser strUser = "DomGuy2"

' Bind to Active Directory, Users container.

Set objRootLDAP = GetObject("LDAP://rootDSE") Set objContainer = GetObject("LDAP://cn=Users," & _ objRootLDAP.Get("defaultNamingContext"))

' Build the actual User.

Set objNewUser = objContainer.Create("User", "cn=" & strUser) objNewUser.Put "sAMAccountName", strUser

objNewUser.SetInfo WScript.Quit

(24)

Introduction to VBScript.doc By Guy Thomas

Page 23 of 59

VBScript Tutorial

-

Learning Points

Note 1: The first 10 lines explain the purpose of the script and declare the variables.

Note 2: The simple, but clever command, which allows the script to work with any domain is: GetObject("LDAP://rootDSE"). Crucially, this statement binds WSH / VBScript to Active directory. The next line puts the focus on the Users container, as that is where the user will be born. Incidentally, the correct syntax is cn=users, whereas OUs that you create need the OU= prefix, for example OU=Accounts,.

Note 3: sAMAccountName controls the logon name, this is the name that users should enter in the dialog box after they press the Ctrl Alt Delete, logon

sequence.

Note 4: .Create is a method to build an object. See how we script "User" not "Computer" or "OU".

Note 5: When creating or modifying users, invariably you need .put and

.SetInfo. The .put method is the equivalent of selecting a box in Active Directory Uses and Computers, in this example, sAMAccountName sets the correct property and .put unloads the value set by strUser. .SetInfo is the VBScript equivalent of  pressing the OK button in the GUI. In both cases, it represents the final act of  creating or modifying the User object.

Note 6: This script represents 'work in progress'. For a real production script you would need to enable the account, and most likely, add several other

properties, for example givenName. My desire is to get you started. Build the script in stages, understand each component, then add another section.

Incidentally, I have an ebook dedicated to all aspects of bulk importing users from data in a spreadsheet.

(25)

Introduction to VBScript.doc By Guy Thomas

Page 24 of 59

Example 2: Script to Create a User in a Named OU (Organizational

Unit)

Prerequisites

Create a new OU. I called my OU Accounts, what name will you choose?

Instructions for Creating a User Account in a Named OU

1. Copy and paste the example script below into notepad or a VBScript editor.

2. Find the strContainer, and then change to the name of your OU. 3. Decide whether to change the value for strUser.

4. Save the file with a .vbs extension, for example: UserOU.vbs. 5. Double click UserOU.vbs and check the Computers container for

strComputer.

' UserOU.vbs

' Sample VBScript to create a User in a named OU. ' Author Guy Thomas http://Userperformance.co.uk/ ' Version 2.4 - September 2005

' ---' Option Explicit

Dim objRootLDAP, objContainer, objUser, objShell Dim strUser, strName, strContainer

strUser = "BookKeeper21" strName = "Bookie"

strContainer = "OU=Accounts ," ' Note the comma ' Bind to Active Directory, Users container.

Set objRootLDAP = GetObject("LDAP://rootDSE")

Set objContainer = GetObject("LDAP://" & strContainer & _ objRootLDAP.Get("defaultNamingContext"))

' Build the actual User.

Set objUser = objContainer.Create("User", "cn=" & strUser) objUser.Put "sAMAccountName", strUser

objUser.Put "givenName", strName objUser.SetInfo

' Optional section to launch Active Directory Uses and Users Set objShell=CreateObject("WScript.Shell")

objShell.Run "%systemroot%\ system32\ dsa.msc" WScript.Quit

' End of Sample UserOU VBScript.

VBScript Tutorial

-

Learning Points

Note 1: The key difference between the two scripts is: strContainer = "OU=Accounts ,". Trace how VBScript applies this variable to set the Organizational Unit.

Note 2: The following command looks easy to script: GetObject("LDAP://" &  strContainer & _. However it took me ages to get the speech marks and

(26)

Introduction to VBScript.doc By Guy Thomas

Page 25 of 59

Note 3: objShell.run. This optional section is merely me having a little fun. What this section does is open the Active Directory Users and Computers MMC ready for you to inspect the new User account. My other reason for adding this code is show that the script has executed successfully; otherwise, I just sit and wonder if VBScript has finished interpreting all the commands.

Note 4: I suggested in Example 1 that you could add other attributes, trace how I added givenName through strName. To see what I mean, I suggest that you alter the value from "Bookie" to a more realistic name.

Summary of Creating User Accounts

The first example script shows you how to create a new user account in the default container of Windows domain. In the second example, we control the name of the OU where the account appears in Active Directory Users and

Computers. The tutorial's hidden agenda is learning how to apply the VBScript object, methods and value technique. There is one other guiding principle, start simply. Build complex scripts in stages.

This page covered the following VBScript methods, commands and syntax:

Set objRootLDAP = GetObject("LDAP://rootDSE") .Create("User"), .Put and .SetInfo

(27)

Introduction to VBScript.doc By Guy Thomas

Page 26 of 59

Section 5

Map Network Drive

Map a Network Drive - A Classic task for a VBScript.

Introduction to MapNetworkDrive

The practical task of this script is to map a network share to a local drive letter. The best example of this tactic is when users access their home folder on a server, via a drive letter. Unlike the Active Directory scripts, this script should execute on any machine.

VBScript has a whole family of methods, which manipulate the network just as if  you used the Windows Explorer; look out for the line which builds the VBScript object: CreateObject("WScript.Network"). The scripting spotlight on this page falls on a VBScript method called MapNetworkDrive. On the next page we will examine the parallel method called AddWindowsPrinterConnection, which maps printers. Similar methods (not covered here) include, RemoveNetworkDrive and EnumNetworkDrives.

Topics for MapNetworkDrive

Our Mission and Goal

Example - MapNetworkDrive VBScript Method Learning Points for MapNetworkDrive

Guy's Challenges

Summary of MapNetworkDrive

Our Mission and Goal

Our mission is to map a network drive. Users may think that their home drive is a local H:\ , but you and I realize that the H:\ is a mapping which represents a folder on a server. There is only a slim chance that a user would know how to create this H:\ drive manually. Moreover, the chances of them remembering to create the drive mapping every time they logon are practically zero.

Consequently, this is a job for a VBScript that runs automatically at logon.

Incidentally, I have an ebook dedicated to all aspects of logon scripts if you want more detail. This page is all about getting you started with VBScript.

MapNetworkDrive Method

MapNetworkDrive follows the VBScript format of object, method, and value. Firstly, we create the network object called objNetwork. Next we employ the MapNetworkDrive method to create the local drive letter. For our examples, we deploy MapNetworkDrive with two arguments, drive letter and UNC path. You can observe in the examples that each argument is controlled by its own variable, strDriveLetter = "H:" and strRemotePath = "\\ alan\ home".

(28)

Introduction to VBScript.doc By Guy Thomas

Page 27 of 59

Example

-

MapNetworkDrive VBScript Method

A reminder, our objective is to map a drive letter to a network path. In this example, H:\ maps the UNC path \\ server\ share. Please note that the reason this script works for me is that my share name is called, ' \ home' and my server is '\\ alan. Consequently, my UNC path for the variable strRemotePath =

"\\ alan\ home".

Pre-requisites.

1. On Line 10, change the server name from '\\ alan' to your server name. 2. Make sure that your server has a share called '\ home'.

Instructions to MapNetworkDrive

1. Copy and paste the script below into notepad.

2. Check strPath, your server is unlikely to be called "\\ alan, so amend to the name of your server.

3. Save the file with .vbs extension e.g. MapNetworkDrive.vbs.

4. Double click your script and check in your Windows Explorer for a new drive called: home on 'alan' (H:).

'

' MapNetworkDrive.vbs

' VBScript to map a network drive to a UNC Path.

' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.4 - September 2005

' ---' Option Explicit

Dim objNetwork

Dim strDriveLetter, strRemotePath strDriveLetter = "H:"

strRemotePath = "\\ alan\ home"

' Purpose of script to create a network object. (objNetwork) ' Then to apply the MapNetworkDrive method. Result H: drive Set objNetwork = WScript.CreateObject("WScript.Network") objNetwork.MapNetworkDrive strDriveLetter, strRemotePath WScript.Quit

' End of Example VBScript.

Learning Points for MapNetworkDrive

Note 1: VBScript is an object based scripting language. On line 14, you can see how the code creates objNetwork. Line 16 then

applies the famous MapNetworkDrive method to achieve the actual drive mapping.

Note 2: If you run the script a second time, then you get WSH error message code 80070055. The temporary solution is to launch Windows Explorer, and then delete the appropriate mapped drive. In my example, right click on: home on 'alan' (H:) and select: Disconnect. (See diagram opposite.) Now you can run the script again. A better solution is to add error-correcting code, however, for now, I want to focus on one goal, mastering MapNetworkDrive.

(29)

Introduction to VBScript.doc By Guy Thomas

Page 28 of 59

Note 3: At the top of the script is a heading section. The idea of the header is to explain what this VBScript will achieve. Some scriptwriters feel that the Dim statements, which declare variables, are also part of the header section.

Note 4: Option Explicit is a VBScript command to force me to declare variables. Not only is this 'best practice', but in my case, it alerts me to typos when I try to use the same variable later in the script.

Note 5: Once we declare strDriveLetter, then we can assign it a value, in this case "H:". One perennial problem I have with scripting is paying attention to detail, especially the syntax. Even with the simple drive letter - H, we must be careful. For the script to succeed we need precisely "H:". Neither "H:\ ", nor "H\ :" will work.

Guy's Challenges

MapNetworkDrive provides an ideal vehicle to explore the personality of  VBScript. Discover what you can change, and what is fixed by VBScript. My

advice is to start by changing strDriveLetter = "H:" to strDriveLetter = "L:"   (or any other available letter). I will be surprised if you fail to map the UNC path to the new letter.

Try changing strDriveLetter to plain strLetter. You should get this working, but only if change strDriveLetter not once, but in three places. If you accept this challenge then Option Explicit will keep you on track. The point is that you have control over the name of the variable.

You could try changing MapNetworkDrive to MapMyHomeDrive, or you could just accept my assurance that you cannot just invent methods to manipulate WScript objects. Instead, you have to learn the rich variety of built-in VBScript methods. My message is never miss an opportunity to learn the name of method, for

example, EnumNetworkDrives, RemoveNetworkDrive and of course MapNetworkDrive.

Summary of MapNetworkDrive

MapNetworkDrive is the classic method that logon scripts employ to provide home directories. Once you master this VBScript, which maps drive letters to UNC

shares, you can extend your range to mapping printers.

This page covered the following VBScript methods, commands and syntax:

Key VBScript term: MapNetworkDrive, observe this method: CreateObject("WScript.Network")

References

Related documents