PowerShell Ezine, Logon Scripts

Guy's Scripting Ezine 53 - Creating Contacts in AD

Contents for Guy's Scripting Ezine 53 - Creating Contacts in Active Directory

This Week's Secret

I firmly believe that God gave us all two ears and only one mouth so that we would listen more than we speak.  Listening to you the reader, I see from the survey results, that you want slightly more complex scripts and Active Directory is your favoured topic.

This Week's Secret is that I am still a little puzzled by WSH (Windows Scripting Host).  If I ignore WSH my scripts don't work.  However, when I investigate WSH, it does not seem to do much.  My conclusion is that WSH is essential to 'bind to' objects, for example Active Directory or network drives.  VBScripts without WSH would be like walls without cement.  The particular WSH 'cement' that we use this week is getObject and createObject.

Guy Recommends:  A Free Trial of the Orion Network Configuration Monitor (NCM) v6Review of Orion NCM v6

Config management of routers, switches and firewalls is fun with NCM (Network Configuration Manager.  Furthermore, it can help to achieve your compliance policy, for example, pinpoint devices not backed up and discover access infringements or even weak passwords.  This Solarwinds NCM suite can not only detect violations, but also upload scripts to correct the problem.

Most computer problems arise from configuration changes.  Thus it makes sense to get a proper monitoring system so that you can double-check that that all the settings confirm to your security policy.

Download your free trial of Orion's Network Configuration Monitor.

This Week's Mission - To create Contacts

We have two distinct strategy for creating our contacts.  The first script is simple, it just shows how to create a single contact using VBScript.  The second method is more versatile and demonstrates how to build contact objects using information stored in a spreadsheet.

Introduction to Creating Contacts in Active Directory

Of all the objects in Active Directory, Contacts would seem to be the simplest object to create.  However, I always want to do more than just produce a script which you slavishly copy.

What we both have to remember is that I do not know the name of your Active Directory domain.  This is why so many of my scripts bind to the Root LDAP name rather than requiring you to replace my domain name with your domain name.  The result is that this script will work on which ever domain you execute the .vbs file.   For reference, here are the lines of code which bind to Active Directory.

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


If you are looking for handy network utilities, try some of the free downloads at Tools4Ever


Example 1 - Create an OU then create a Contact in that OU.

Now I could play safe and create the Contact objects in the Users' container, but it is more exciting and more realistic to create these Contacts in an OU.  However this leads to the question of what shall we call the OU?  Answer: Suppliers.  Next question, should the script create an OU?  Answer Yes. What happens when you run the script and the OU already exists?  Answer: - it fails!  As a well defined problem is half the solution, I hope that you will be alert and amend my script to cure such problems.

JT wrote in with a solution using On Error... See here

(By the way, if you know of an 'IF Exists' method that would apply to the OU problem then do email it to me.  Trust me, I have tried a few methods but to no avail.)

Instructions

  1. Important: Which OU will use?  My script uses OU=Suppliers.  Either accept this name, or change the script to reflect YOUR OU, for example OU=MyContacts.
  2. Optionally, find and change strYourDescription
  3. Copy and paste the script below into notepad or OnScript.
  4. Save the file with .vbs extension e.g. Contact.vbs.
  5. Double click and examine the message boxes.
  6. Check out strContainer

 

 

' Contact.vbs
' Purpose VBScript to create a contact object.
' Learning Points: Creates one contact Object
' Usage where you need contacts for example, suppliers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.3 - November 14th 2004
' --------------------------------------------------------------'
Option Explicit
Dim objRoot, objOU, objDomain, objUser, strYourDescription
Dim strDNS, strContainer, strContactName, strMail

' Set string variables
strContainer = "OU=Suppliers"
strContactName = "cn=MySupplier1"
strMail = "supplier@supplyme.com"
strYourDescription = "Guy's Contact"

' Section to attach to Active Directory
Set objRoot = GetObject("LDAP://rootDSE")
strDNS = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & strDNS)

' Section to create an OU
Set objOU=objDomain.Create("organizationalUnit", strContainer)
objOU.Put "Description", "Guy's Contact OU"
objOU.SetInfo

' Section to create the contact
Set objOU = GetObject("LDAP://"& strContainer & "," & strDNS)
Set objUser = objOU.Create("contact", strContactName)
objUser.Put "Description", strYourDescription
objUser.Put "Mail", strMail
objUser.SetInfo

Wscript.Echo "Look in " & strContainer & " for (F5) " & strMail

' End of example VBScript

Learning Points

Note 1: Binding is a key concept in WSH scripting.  Check out where the script binds with YOUR domain name. See :
Set objRoot = GetObject("LDAP://rootDSE").

Note 2: Once the script 'bound' to Active Directory, did you see the objects that it created?  "OrganizationalUnit" and later "contact".

Note 3: Examine how this script actually creates an OU.  If you run the script for a second time, then either
a) Rem out : ' Section to create an OU.
b) Go to your Active Directory and delete the Suppliers OU.
c) Observe the Error Correcting Code in Example 1a

Note 4: See how this line uses & (ampersand) to join three elements, the OU (strContainer),  a COMMA, and finally your Domain
Set objOU = GetObject("LDAP://" & strContainer &  ","  & strDNS)

Note 5: Check the .Put, and .SetInfo methods which actually form the contact object.  ObjUser.SetInfo then gives birth to the Contact.

Note 6:  See more on Creating Contacts here

ˇ

Example 1a - With Error correcting code thanks to John T.

This script incorporates On Error Resume Next.  It also uses
If Err.Number <> 0 Then... To catch and then correct the error.  Many thanks to John T for suggesting the error correcting code.

 

' Contact.vbs
' Purpose VBScript to create a contact object.
' Learning Points: Create contact
' Usage where you need contacts for example, suppliers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.3 - November 14th 2004
' --------------------------------------------------------------'
Option Explicit
Dim objRoot, objOU, objDomain, objUser, objExcel, objSheet
Dim strDNS, strContainer, strContactName, strPathExcel, strMail
Dim strYourDescription

' Set string variables
strContainer = "OU=Suppliers"
strContactName = "cn=MySupplier1"
strMail = "supplier@supplyme.com"
strYourDescription = "Guy's Contact"

' Section to attach to Active Directory
Set objRoot = GetObject("LDAP://rootDSE")
strDNS = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & strDNS)

' Section to create an OU
On Error Resume Next
Set objOU=objDomain.Create("organizationalUnit", strContainer)
objOU.Put "Description", "Guy's Contact OU"
objOU.SetInfo

' Err correcting code thanks to John T
If Err.Number <> 0 Then
Err.Clear
objOU=objDomain.Delete("organizationalUnit", strContainer)
Set objOU=objDomain.Create("organizationalUnit", strContainer)
On Error GoTo 0
End If

' Section to create the contact
On Error Resume Next
Set objOU = GetObject("LDAP://"& strContainer & "," & strDNS)
Set objUser = objOU.Create("contact", strContactName)
objUser.Put "Description", strYourDescription
objUser.Put "Mail", strMail
objUser.SetInfo

' Err correcting code thanks to John T
If Err.Number <> 0 Then
Err.Clear
objUser=objOU.Delete("Contact", strContactName)
Set objOU = GetObject("LDAP://"& strContainer & "," & strDNS)
Set objUser = objOU.Create("contact", strContactName)
objUser.Put "Description", strYourDescription
objUser.Put "Mail", strMail
objUser.SetInfo
On Error GoTo 0
End If

Wscript.Echo "Look in " & strContainer & " for (F5) " & strMail

 

 

Example 2 - Create Contacts by importing their names and addresses from an Excel Spreadsheet.

The last time that I mentioned using a spreadsheet to import data, 99% of readers were thrilled with the extra dimension provided by a Do.. While...loop.  This technique of reading data from cells is essential for a bulk import.  However, Mr Angry wrote in and complained because he needed Excel on the machine in order for my script to work.  Sorry Mr Angry, but once again you will need Excel in order to give my script a chance of reading from a spreadsheet.

Example 2 follows on from the first example with the addition of the following assumptions:

Assumption 1: You have an OU called Suppliers.

Assumption 2: You have Excel!  In Excel you put the names of your contacts in Column A and the corresponding email addresses in Column B.

Spreadsheet Example:

Row 1 Name     Email

Row 2 Guido     guido@somewhere.net

Row 3 Wally     wally@wallyville.org

Example of a very simple Spreadsheet Download here

Assumption 3: You understand and can modify:
strPathExcel = "E:\Files\contacts.xls"

 

' ContactExcel.vbs
' Purpose VBScript to create a contact object.
' Learning Points: Create contacts from Excel
' Usage where you need contacts for example, suppliers
' Author Guy Thomas http://computerperformance.co.uk/
' Version 2.1 - November 14th 2004
' --------------------------------------------------------------'

Option Explicit
Dim objRoot, objOU, objDomain, objUser, objExcel, objSheet
Dim strDNS, strContainer, strContactName, strPathExcel, strMail
Dim intRow, strExcelContact, strYourDescription

' Set string variables
' Note: Assume an OU called suppliers exists.
strContainer = "OU=Suppliers"
strPathExcel = "E:\Files\contacts.xls"
strYourDescription = "Guy's Contact"
intRow = 2

' Section to attach to Active Directory
Set objRoot = GetObject("LDAP://rootDSE")
strDNS = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & strDNS)

' Get Names from Excel
strPathExcel = "e:\Files\contacts.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open strPathExcel
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

intRow = 2 ' Means second row in Spreadsheet
' intRow, 3 means 3rd COLUMN C, (,6 means columns F)

Do
strExcelContact = Trim(objSheet.Cells(intRow,1).Value)
strMail= Trim(objSheet.Cells(intRow,2).Value)

If strExcelContact <> "" then
strContactName = "cn=" & strExcelContact
' Else strContactName ="cn=last"
End if

' Section to create the contact
Set objOU = GetObject("LDAP://"& strContainer & "," & strDNS)
Set objUser = objOU.Create("contact", strContactName)
objUser.Put "Description", strYourDescription
objUser.Put "Mail", strMail

' Section to prevent errors caused by blank email address
If strExcelContact <> "" then
objUser.SetInfo
End if

intRow = intRow + 1

' Note: Next line was for Troubleshooting
' wscript.Echo "strExcelContact " & strExcelContact
Loop until strExcelContact = ""

' To avoid lots of Excel instances is task manager
objExcel.Quit

Wscript.Echo "Success " & intRow -2 & " Contacts in " & strContainer

WSCript.Quit

' End of example VBScript

Learning Points

Note 1: Go back through the script and check through all the ' Comments between each section.

Note 2: If you are looking for a challenge, then try shortening the script.  Perhaps only use one variable strContact where I have used two, strExcelContact and strContactName.

Note 3: Should you be able to come up with an 'If Exists' to check on the OU (strContainer) I will be mightily impressed and offer you a free ebook of your choice. (JT Wrote in with a solution)

Summary: Creating Contacts

If you need to add lots Contacts to Active Directory then consider a VBScript.  In cases where you already have the names and email addresses in a spreadsheet, it makes good sense to design a VBScript to import the names and email addresses.

Computer Training Software - Recommended Training VideosGuy Thomas recommends Computer Training Software

Their topics and material are ideal for getting you started with VBScript.  The videos are easy to follow and you can control the pace.  Try their free demo material and then see if you want to buy the full package. See more about VB Script Training CD.


 *


Google

Web  This website

Guy Recommends: SolarWinds Engineer's Toolset v10Engineer's Toolset v10

The Engineer's Toolset v10 provides a comprehensive console of utilities for troubleshooting computer problems.

There are so many good gadgets, it's like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.  Download your copy of the Engineer's Toolset v 10

 

Home Copyright © 1999-2010 Computer Performance LTD All rights reserved.

Please report a broken link, or an error.