Scripting and Managed Code Demystified

Complete a simple administrative task in four languages

Ethan Wilansky

August 15, 2004

9 Min Read
ITPro Today logo in a gray background | ITPro Today


I'm always amazed to observe how apassion for technology often morphsinto a religion. An example of this phenomenonis the various Perl andVBScript scripting zealots. Each languagehas its place, as do programminglanguages such as C# and VisualBasic .NET. However, drawing linesbetween these languages is pointlessand nonproductive.

Rather than point out differences, Iwant to show you how similar thecode can be among Perl, VBScript, C#,and Visual Basic .NET. To do so, I'llshow you how to complete a simplebut important task—creating anActive Directory (AD) user account—in all four of those languages. (I'veopted not to show you how to displayHello World on the console in all fourlanguages—a simple procedure butone of the most overscrutinized programmingtasks.)

Defining Terms
Regardless of the language youchoose, creating an AD object—suchas a user account—involves the followingfour steps:

  1. Connect to the AD container inwhich you want to create the object.

  2. Create the object.

  3. Set any mandatory attributes thatAD doesn't set automatically.

  4. Save the object to AD.

You might be asking, "If that's all thereis to it, why have I seen code examplesfor creating a user account that contain300 or more lines of code?" Youneed to be precise about the type ofcode examples. Generally, you'llencounter two types: those that areinstructive and those that show completesolutions.

There's a big difference betweenan instructive code example and acomplete code solution. A completecode solution for creating useraccounts will contain error handling(e.g., to check for an existing useraccount before creating a new one),console output, and perhaps otherprocedures. For example, a completecode solution might read from aspreadsheet containing user accountinformation, then use that informationto generate user accounts. In contrast,an instructive code example will showonly the essential steps necessary forcompleting a task. An instructive codeexample for creating an AD useraccount will therefore contain onlyfour or five lines of code. Of course, thisdistinction between a code solutionand a code example isn't limited to ADuser account creation. You can reducealmost any systems administrationtask to a few lines of code, regardless ofthe language in which you write it.

Choosing Languages
To demonstrate the task of AD useraccount creation, I chose two scriptinglanguages (VBScript and Perl) andtwo programming languages (VisualBasic .NET and C#). VBScript isarguably the easiest language tounderstand, and it's a language thatMicrosoft fully supports for Windowssystems administration. Perl is a naturalchoice because it's a pervasivecross-platform scripting language thatmany Windows administrators andUNIX and Linux administrators use. Ichose Visual Basic .NET and C#because they're both included withthe Windows .NET Framework and arethe most popular languages in theFramework. In addition, if you'refamiliar with Visual Basic (VB) orVBScript, Visual Basic .NET is easy tounderstand. If you're familiar withJScript or Java, C# is easy to follow.

Putting It Simply
If you've never coded in any languagebefore, don't despair. You'll be surprisedby how easily you can programin any of these languages when you isolatea specific task from all the otherstuff that surrounds the code. Somepeople might argue that this is an oversimplificationof scripting and developmentin general. However, the key toworking with any technology discipline,programming or otherwise, isstarting with simple examples thatdemonstrate the completion of a basictask. After you see how to apply a technology,you're better prepared to diginto the intricacies of a robust andpowerful discipline such as programming.The code in Listing 1, Listing 2,Listing 3, and Listing 4 performs the followingsteps to create a user account:

  1. Connects to the TechWritersorganizational unit (OU) in the fabrikam.com domain.

  2. Creates a user account namedKen Myer.

  3. Sets the sAMAccountName mandatoryattribute to MyerKen.

  4. Saves the user account to theTechWriters OU.

But don't try to run the code yet! Youmust complete some preliminarytasks. First, you need to configureyour client and server environment ina specific way to run these examples.Second, you must verify that theunderlying client infrastructure canrun the code. Third, except for VBScript,you must add a line or two ofcode to supplement the actual taskcode. Let's walk through each step.

Configuring the Client and Server
To get started, you need to ensure thatyour computer (the client) is a memberof an AD domain named fabrikam.com with an OU named TechWriters.Also, a user account with a sAMAccountNameof MyerKen must notexist in the domain, and the Tech-Writers OU must not contain a useraccount with a CN value equal to KenMyer.

I could have made the examplesmore dynamic, but doing so wouldhave added complexity to the codeexamples, thus defeating the primarypurpose of this article—to createinstructional code examples. Thatbeing said, you can modify the taskcode that appears in the listings topoint to a different domain or to createa user account with a differentname. Here are some examples ofchanges you can make:

  • In line 1, change ou=TechWriters,dc=fabrikam,dc=com to ou=HR,dc=adatum,dc=com to connect to theHR OU in the adatum.comdomain.

  • In line 2, change CN=Ken Myer to CN=John Doe to use the name JohnDoe instead of Ken Myer.

  • In line 3, change MyerKen to Doe-John to specify a sAMAccountNameof DoeJohn instead of MyerKen.

Preparing the Scripting Environment
The scripting languages require ascripting engine, language interpreters,and COM objects to completetasks. Windows Script Host (WSH) isthe Windows scripting engine that letsyou run scripts. Even though Windows2000 and later include WSH by default,you should upgrade to WSH 5.6 for allWindows platforms except WindowsServer 2003. Windows 2003 comeswith the most recent build of WSH 5.6.You can find WSH 5.6 at http://msdn.microsoft.com/scripting.

WSH can run VBScript code out ofthe box because WSH includes theVBScript language interpreter. In contrast,Microsoft doesn't provide a Perlinterpreter in WSH, but you can easilyinstall one. Go to http://www.activestate.com/products/download/download.plex?id=activeperl to downloadand install a Windows Installer (MSI)file of ActivePerl 5.8.1 or later. After youinstall the Perl interpreter, you can runPerl scripts in WSH.

The COM objects for administeringAD from scripts are contained inActive Directory Service Interfaces(ADSI). Win2K and later include ADSI.For Windows NT 4.0 Service Pack 6a(SP6a) and Windows 9x users, Microsofthas created the AD Client Extensions.The Win9x-based clientextensions are contained on theWin2K installation CD-ROM. You candownload the AD Client Extensionsfor NT Workstation 4.0 from http://www.microsoft.com/ntworkstation/downloads/other/adclient.asp.

Preparing the Managed Code Environment
The managed code languages (VisualBasic .NET and C#, in these examples)require Microsoft .NET classes to completetasks. Windows 2003 and laterinclude the .NET classes. For mostother Windows OSs, you can download.NET Framework 1.1, which containsthe .NET classes and other importanttools, from Microsoft WindowsUpdate. When you check for updatesfrom a computer that doesn't have.NET Framework 1.1, .NET Framework1.1 appears at the Microsoft WindowsUpdate site in the Pick updates toinstall menu, underWindows or WindowsXP, depending on the OS fromwhich you run the update.

.NET Framework 1.1 operates onWindows 2003, Windows XP, Win2K,Windows Me, and Win98 computers.You must also be running MicrosoftInternet Explorer (IE) 5.01 or later. Ifyou're unsure whether you're running.NET Framework 1.1, go to the ControlPanel Add/Remove Programs appletand look for a Microsoft .NET Framework1.1 entry. You can also search forthe %windir%Microsoft.NETFrameworkv1.1.4322 path. The foldername's 4322 designation is the buildnumber of version 1.1 of the Frameworkand is the current build numberas of December 2003. To learnmore about the Framework, checkout http://msdn.microsoft.com/netframework.

Compiling Code
WSH interprets scripts at runtime,which means you don't have to compilethem to run. However, you mustcompile managed code before it willrun. For large, complex code, compiledprograms run faster than interpretedcode and compiled code isinherently more secure. There's a lotmore to understand about interpretedand compiled code, but for the purposeof this article, all you need toknow is that you must compile managedcode before you run it.

The Framework includes twoimportant tools for compiling themanaged code examples. For VisualBasic .NET, the name of the command-line compiler is vbc.exe. For C#,it's csc.exe. Both of these applicationsreside in the Framework parent directory.In the case of .NET Framework1.1, this directory is the v1.1.4322folder. For the sake of convenience, Irecommend that you add the%windir%Microsoft.NETFrameworkv1.1.4322 path to your Pathenvironment variable so that you don'thave to specify the entire path to runthe compilers. (Replace %windir%with the location of your Windowsdirectory.) Of course, if you have VisualStudio .NET installed, you won't needto navigate to the parent folder thatcontains the Framework or add a pathspecification to your Path environmentvariable to compile managedcode. Instead, you can compile yourcode by using the Visual Studio .NETcommand prompt or the Visual Studio.NET IDE.

Before you compile the C# andVisual Basic .NET examples, you needto add a few more lines of code. In thenext section, I describe those additions,then provide you with the compilercommand and parameters youneed to compile the sample code.

Preparing the Examples
Each piece of sample code requiressome minor preparation before it'sready to run. For the VBScript example,copy the code in Listing 1 to a textfile, then save the file as listing1.vbs.You can save all code examples to thesame folder.

For the Perl example, you must add use Win32::OLE to the top of the file, as Listing 5, shows. Win32::OLE isthe name of a Perl module that provides,among other things, the ability touse Windows' COM-based libraries¡ªspecifically, for this example, the COMbasedlibraries in ADSI. Copy the codein Listing 5 to a text file, then save thefile with a .pl extension.

For the Visual Basic .NET and C#examples, you must add a few lines ofcode to the beginning and end of thecode, as Listing 6 and Listing 7 show.These additional code lines arerequired but aren't specific to theexamples. The sidebar "The VisualBasic .NET and C# Surrounding Code"provides more information aboutthese additional lines of code.

To compile the Visual Basic .NETexample, copy the code in Listing 6 toa text file, then save the file as listing6.vb. From the command prompt,navigate to the file folder and run thecommand

vbc /t:exe /r:system.dll/r:system.directoryservies.dll listing6.vb

to create a program named listing6.exe. The Vbc command-line tool, partof the Framework, lets you compilesource code written in Visual Basic.NET into an application from thecommand line. The /r switches tell theVbc program which DLLs containclasses required to run the application.These DLLs are included with theFramework. The listing6.vb filename isthe name of the file that contains thesource code the command.

To compile the C# example, copythe code in Listing 7 to a text file, thensave the file as listing7.cs. From thecommand prompt, navigate to the filefolder and run the command

csc /t:exe /r:system.directoryservices.dlllisting7.cs

to create a program named listing7.exe. In this case, the Framework's Csccommand-line tool lets you compilesource code written in C# into anapplication. The switches work similarlyto the Vbc example for compilingVisual Basic .NET code from the commandline. However, you don't need tospecify the system.dll class when compilingthe C# example.

Running the Examples
For consistency, each code exampleuses the same OU, the same CN (KenMyer), and the same sAMAcccount-Name (MyerKen). Therefore, after runningeach code sample successfully,open the Microsoft Management Console(MMC) AD Users and Computerssnap-in and delete the Ken Myer useraccount in the TechWriters OU priorto running the next code sample. Torun each sample, double-click thescript file or compiled code. Alternatively,go to the command prompt,navigate to the file folder, type thename of the file, and press Enter.

Are You Encouraged?
You now know how to create an ADuser account in four different codinglanguages. The key is stripping a taskdown to its core and working fromthere. Each language presents a surprisinglysimilar approach to codingthe task.

In upcoming articles, I'll augmentthis task so that you can specify useraccount information from the commandline, create multiple useraccounts, and handle errors. Beyondthat, my goal is to continue to enlightenyou about the relative ease with whichyou can complete other crucial systemsadministration tasks from all of theselanguages.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like