|
VBScript or Perl?The Windows Sys Admin's Scripting Dilemmaby Robbie Allen, coauthor of Active Directory, 2nd Edition, and author of the recently released Active Directory Cookbook11/18/2003 |
As I was working on Active Directory Cookbook, I had to make a decision that many Windows system administrators face at one point or another: whether to use VBScript or Perl? I'm a long-time Perl guy, but unfortunately, no matter how much I preach the benefits of Perl, the Windows sysadmin community hasn't embraced Perl the way it has been embraced on the Unix side. Ultimately I decided to use VBScript because it is the least common denominator as far as scripting languages go on the Windows platform (besides batch files, of course). I did, however, include Perl examples on my web site so as not to leave out the Perl coders.
I was able to take the easy way out by using both in this case, but most system admins only need one, but which one? I've already stated my preference towards Perl, but I want to outline the pros and cons of each because both languages have their place. You can accomplish most of the basic system admin tasks with either language. For this reason you'll need to look at the other advantages and disadvantages of each language to determine which works best for you.
Overview of VBScript
VBScript is a subset of the Visual Basic programming language. You can run VBScript code using a Windows Scripting Host interpreter (wscript.exe or cscript.exe) or from within Active Server Pages (ASP).
Advantages of VBScript
No installation required
This is the number one reason VBScript is so widely used. Since you can run VBScript code on any Windows 2000 and later computer without needing to install anything, this makes it much easier to support on a lot of computers.
Popular on Windows
Because VBScript comes out of the box with Windows and was developed by Microsoft, naturally there is better support for it; not only by Microsoft, which documents VBScript extensively on the Microsoft Developer Network (MSDN), but also on other non-Microsoft web sites. Generally, it is much easier to find VBScript examples than Perl examples (for Windows).
Built-in support for COM Automation and WSH
To do much of anything with Windows, you need to use a COM-based API, such as ADSI or WMI. For scripting languages, a subset of COM is supported, which is called the COM automation interface. VBScript can use this directly with the GetObject and CreateObject functions. With Perl, you have to use Win32::OLE module to access COM objects. Here is an example that uses the VBScript
GetObjectfunction:set colUsers = GetObject("LDAP://cn=users,dc=rallencorp,dc=com")And here is the same thing using Perl:
use Win32::OLE; $colUsers = Win32::OLE->GetObject("LDAP://cn=users,dc=rallencorp,dc=com")Readable
VBScript code is generally very readable. Here is some sample VBScript code that should be pretty easy for even non-programmers to decipher:
set colUsers = GetObject("LDAP://cn=users,dc=rallencorp,dc=com") for each objUser in colUsers WScript.Echo objUser.Name nextHere is the equivalent Perl code, which is slightly less readable:
use Win32::OLE 'in'; $colUsers = Win32::OLE->GetObject("LDAP://cn=users,dc=rallencorp,dc=com") foreach $objUser (in $colUsers) { print $objUser->Name,"\n"; }Easy transition for VB programmers
VBScript is a derivative of Visual Basic (VB) so if you know a little VB, it is easy to pick up VBScript.
Disadvantages of VBScript
Limited command-line parsing and GUI support
The built-in support for parsing command-line options and generating graphical interfaces (such as a password prompt) are pretty limited in VBScript.
Awkward and wordy language constructs
I mentioned that VBScript is very readable, but this also makes VBScript wordy in comparison to Perl. Because VBScript treats everything like an object, it often results in awkward language constructs. Perhaps the worst offender is VBScript regular expressions. Here is a simple example that tests if a string contains the letters "www" in it:
strMatch = "www.rallencorp.com" set objRegEx = New RegExp with objRegEx .Pattern = "www" .IgnoreCase = True .Global = True end with if objRegEx.Test(strMatch) then WScript.Echo "Matched" else WScript.Echo "Did not match" end ifNow here is the same example in Perl:
$match = "www.rallencorp.com"; if ($match =~ /www/i) { print "Matched\n"; } else { print "Did not match\n"; }Limited third-party module/add-on support
This is one of the biggest issues with VBScript. Unlike Perl, there is no large VBScript repository where programmers freely contribute and share code in the form of packaged modules or components. There are many repositories that contain sample scripts, but none that I've seen that are on the same scale as CPAN for Perl.
No command-line code execution support
Being able to execute and test code from a command-line is an extremely useful feature of a scripting language. With Perl you can use the -e switch and execute code directly. Here is an example that prints the current time:
C:\> perl -e "print scalar localtime"There is no counterpart to this in VBScript.
Uncertain future
At this point, it is hard to tell what will become of VBScript. Microsoft did not provide native support for VBScript within the .NET Framework, choosing to support JScript instead. And there are already rumors flying that in the next major release of Windows, codename Longhorn, there will be a new Microsoft Shell (MSH) that will include a new scripting language. If that happens, more than likely VBScript will start to fade away.
|
Related Reading
VBScript in a Nutshell |
Overview of Perl on Windows
Perl has a long history dating back to 1987 when Larry Wall released the first version. Now, an army of dedicated Perl hackers actively maintain Perl, and ports exist for virtually every modern operating system.
Advantages of Perl
Robust
As far as scripting languages go, Perl ranks at or near the top for being the most robust and full-featured.
Extensive module support
If I had to give one reason to choose Perl over VBScript, this would be it. The Comprehensive Perl Archive Network (CPAN) contains an extensive collection of Perl modules that you can use to do just about anything you can think of. As far as Microsoft technologies go, the Win32:: module namespace contains modules for manipulating the registry, generating GUIs, manipulating files, using the Win32 API, and much more. If you've wondered if someone has already written code to do a particular function, odds are it is in a module somewhere in CPAN. Visit http://www.cpan.org/ for more.
Cross-platform
If you work in an environment that has a mix of Microsoft and non-Microsoft operating systems, Perl is your best bet. And depending on what you need to do, you can even write Perl code that works cross-platform.
Actively developed
A large effort has been underway since 1999 to develop the next major version of Perl, Perl 6, which is a complete rewrite of the language.
Disadvantages of Perl
Requires installation
This isn't a big deal, but it is something you have to consider if you want to use Perl across a large number of systems. You can download Perl for free from the ActiveState site. ActiveState provides a number of extras that you can buy if you want to build .NET components, run Perl scripts as services, create executables from Perl scripts, and so on.
Daunting for newcomers
I hear this one quite a bit. Often when people see Perl code for the first time, they write it off as being too complicated to learn without a programming background. It is true that Perl can be extremely hard to read if not written well, but that is due more to the flexibility and capabilities of the language. You can write readable Perl code just as easy as you can write unreadable Perl code.
Limited support by Microsoft
I debated whether to include this as a disadvantage or not, but after several years of developing large Perl applications on Windows, it is apparent to me that Microsoft doesn't like to deal with problems that arise through the use of Perl. Often when I'd find an apparent bug in a Microsoft API, they wouldn't look at the Perl code, but instead required that the error be duplicated using VBScript or VB. It is unlikely you'll find something you can't workaround, but just be aware that if you do encounter a potential bug, you may want to show it to Microsoft in one of their languages to get quicker resolution.
Summary
If you want to get serious about automation in the Windows environment, I recommend using Perl because of its extensive module support and the overall robustness of the language. If you only want to do something quick and dirty or you don't have any programming experience, VBScript is probably your better bet.
As far as other scripting languages go, a case could be made for using JScript because of its integration with the .NET Framework, but I don't find many people using JScript for system admin tasks. I'll leave that for someone else to argue.
O'Reilly & Associates recently released (September 2003) Active Directory Cookbook for Windows Server 2003 & Windows 2000.
Sample Chapter 8, Computers, is available free online.
You can also look at the Table of Contents, the Index, and the Full Description of the book.
For more information, or to order the book, click here.
Robbie Allen is the coauthor of Active Directory, 2nd Edition and the author of the Active Directory Cookbook.
Return to the O'Reilly Network.
Showing messages 1 through 33 of 33.
-
perl does NOT need instalation for windows
2006-05-05 19:07:30 evenprime [View]
-
VBScript or Perl? The Windows System Administrator's Scripting Dilemma
2006-01-19 12:01:44 drwjr [View]
For Windows, I'm not sure I'd use either. I'm currently trying to learn both VBScript and Perl, because they are commonly available at most corporate IT environments.
But I've been a Winbatch scripter for years. I find Winbatch to be much more robust than VBScript, it does cost (but it doesn't cost much), it does have to be installed (though I hardly find that to be a big deal), it has support for third party development of add-on modules, and it doesn't necessarily require an interpretive environment like VBScript does (because you can compile your Winbatch scripts into freely-distributable stand-alone executables).
-
VBScript disadvantages...
2004-11-01 12:59:16 regisdesrosiers [View]
Corrections:
VBScript has command line parsing support as long as you put your code in a WSF file. You can then access arguments with WScript.Arguments.
As for the GUI, you can get a very flexible GUI system by putting your code in a HTA.
Your wordy VBScript example could have been written clearly by using a function that return a fully defined RegEx object somewhere else in your code:
Function MyRegEx(Pattern)
Set MyRegEx = New RegExp
MyRegEx.Pattern = Pattern
MyRegEx.IgnoreCase = True
MyRegEx.Global = True
End Function
Then you code become less awkward than Perl.
if MyRegEx("www").Test("www.rallencorp.com") then
WScript.Echo "Matched"
else
WScript.Echo "Did not match"
end if
You cannot directly execute code from the command line but it is really not complicated to do a script that will using the Execute method.
As for the future of VBS, the transition from VBS to VB.NET is really smooth if you do not insist on compiling strict. Much smoother than from VB6 in fact. When you have added parenthesis when calling subs you are pretty much done.
-
Portability May Be A Must
2003-12-17 03:25:49 anonymous2 [View]
I'd usually choose Perl for one huge reason: the code, if well written, can always run either on Windows or Linux. Even if we're talking about ASP applications (once I deployed on Linux a site application written in Perl/ASP on a NT4 box). What I really can't understand is why Perl is not more widely used, once it's far more productive than Java, for instance, it's not property of anyone and it's so feature rich! Maybe it's the lack of marketing effort (marketing seems to be everything in these days...).
-
Why not Ruby
2003-12-09 23:46:12 anonymous2 [View]
Just a question :-)
I am using perl at the moment, but it does seem like Ruby is starting to catch a lot of peoples attention...
-
Why not Ruby
2003-12-09 23:45:59 anonymous2 [View]
Just a question :-)
I am using perl at the moment, but it does seem like Ruby is starting to catch a lot of peoples attention...
-
VBScript is a dead language
2003-11-26 19:38:11 anonymous2 [View]
Surprised this hasn't been mentioned yet. M$ sees no future for VBScript. In ASP, VBScript has been supplanted by the new language VB.NET. In batch programming there is another new language (I don't remember/care) to replace VBScript.
-
More considerations
2003-11-24 14:30:54 brianiac [View]
VBScript Strengths
[Formatting Functions]
FormatCurrency(), FormatDateTime(), FormatNumber(), and FormatPercent() not only make short work of tedious formatting tasks, but also use locale-specific formatting rules.
[Data Conversion]
CBool(), CByte(), CCur(), CDate(), CDbl(), CInt(), CLng(), CSng(), CStr(), CBool() all tend to overreact to unconvertable data, but are nicely complemented by VarType(), IsDate(), IsEmpty(), IsNull(), IsNumeric(), and IsObject(). Hex() and Oct() allow converting numbers to non-decimal strings. DateValue() and TimeValue() allow returning just the parsed date or time values, respectively.
[Date/Time Support]
Along with the usual functions for individual date fields, Day(), Hour(), Minute(), Month(), MonthName(), Second(), Timer(), Weekday(), WeekdayName(), Year(), and the more generic DatePart(), there are some more granular functions for current info: Now(), Date(), Time(). The DateSerial() and TimeSerial() functions allow for complex date arithmetic, as do DateAdd(), DateDiff(). Date literals are supported, using # as the delimiter: #datestring#.
VBScript Weaknesses
[Unforgivably Bad Array Support]
While standard functions like Filter(), Join(), and Split() are supplied; no sort, slice, splice, or concatenation functions exist. The stack and queue functions: push, pop, shift, and unshift are also missing.
[Clumsy Exception Handling]
Automatic exception handling has two modes: on (all errors and warnings are fatal), and off.
[Unreasonably Strong Typing]
Objects are not first-class objects; assignment, for example, is handled completely differently from built-in datatypes. This precludes, among other things, programs from passing functions as arguments. Adding to this difficulty, naught is expressed in many distinct (and confusing) terms: Nothing is an invalid object variable, Null adds the database-style complexity of three-valued logic (not true, not false), and Empty is the value in an uninitialized variable. Numeric values can be interpreted as booleans, as can some string values (but only if they are numeric or boolean strings).
JScript Strengths
[Strong Array Support]
A reasonable complement of expected array functions is supported: sort(), split(), join(), slice(), splice(), concat(), push(), pop(), shift(), unshift(), and reverse(). No grep/filter, search, or membership-test function exist.
[Native Associative Arrays (hashes)]
Actually, all JScript arrays are hashes: an array with numeric keys can have string keys added, and all keys can be iterated via the for...in loop. As Perl programmers already know, native hash support allows arbitrarily complex data structures to be built quite easily.
[Structured Exception Handling]
Using try...catch, errors can be handled much more readably, maintainably, and conveniently.
JScript Weaknesses
[NO Formatting Abilities]
All languages should have some kind of formatting ability: C's (and Perl's) printf, C++'s iomanip.h library, Python's % operator, etc. JScript does not. Doing something as simple as including exactly two digits after the decimal when converting a number to a string, or commafiying a number, is incredibly tedious.
[Limited Data Conversion Support]
Dates and non-decimal numbers are not always converted easily. No native currency type is supported.
[Date/Time Support]
No functions exist specifically for date/time arithmetic, and there is an inadequate granularity for parsing control. No date literal is supported. -
Function Pointers
2004-05-11 20:14:46 tby@yehl.us [View]
It is possible to get a "function pointer" in VBS: GetRef.
-
More considerations
2003-12-31 02:08:28 anonymous2 [View]
"all JScript arrays are hashes: an array with numeric keys can have string keys added, and all keys can be iterated via the for...in loop. As Perl programmers already know, native hash support allows arbitrarily complex data structures to be built quite easily."
Actually, JScript (ECMAScript) support of associative arrays is not very useful. You cannot get as the keys (indices) and let's say sort them, as you can in Perl. This prevents popular data-structures, such as frequency hashes.
For example this functionality of Perl would be quite impossible under Perl.
foreach $key (sort {$a <=> $b} keys %hash) {
printf "%s %s", $hash{$key} $key
}
However, this could be emulated in JScript (or any other language) using array of an array.
Another nice thing about Perl, not found in other languages is list/array slicing, such as this:
foreach $line (<FILE>) {
my ($empno, $name, $salary) = (split /,/)[0,2,4];
}
The above slices out the 1st, 3rd, and 5th elements of a CSV file and stores them into local variables called empno, name, and salary. In JScript, this gets a little ugly, and in other languages it gets uglier.
- Joaquin Menchaca -
More considerations
2004-01-06 08:14:11 brianiac [View]
Extracting keys from a JScript array is ugly, but not impossible:
var hash= { 'one': 'first', ... }, keys= {};
for(key in hash) keys.push();
keys= keys.sort();
Slicing is also supported, though only for contiguous regions:
var slice234= arr.slice(2,4); -
More considerations
2003-11-30 12:03:53 anonymous2 [View]
1) I definitely would not take the formating functions of VBScript as a strong point. They are almost useless. Using the system locale specific rules is quite often a bad idea. Especialy for web based projects and for log files. I would really love to get logfiles with differently formated dates from different computers.
But you are right, it's a surprise there is at least this.
2) Data conversion in VB is also horrible. Especialy thanks to the complete evaluation of conditions. The fact that I can't write
IF IsNumeric(foo) AND CInt(foo) > 0 Then
is driving me crazy every time I have to use VB(Script).
Jenda
-
VBScript
2003-11-24 01:52:44 anonymous2 [View]
I find VBScript daunting because of its wordy syntax. But all in all I always like to choose a cross-platform scripting solution.
-
Ah Perl...that IS the answer
2003-11-21 14:16:08 anonymous2 [View]
"The very fact that it's possible to write messy programs in Perl is also what makes it possible to write programs that are cleaner in Perl than they could ever be in a language that attempts to enforce cleanliness. The potential for greater good goes right along with the potential for greater evil." -- Larry Wall
-
Great article
2003-11-19 08:30:13 wjgilmore [View]
During a recent migration to an MS-driven collaboration environment, we faced the same language dilemma. Longtime Perl programmers, we were (and remain) appalled by the thought of having to use vbscript to automate various system-oriented tasks. In terms of power and flexibility, there really can be no comparison between the two (ih our humble opinions, of course). We found Perl (specifically ActiveState's ActivePerl) to be quite adept for the job, particularly the Win32/Directory Services features, and have used it extensively over the past few months.
We did however find that VBScript was better able to perform certain very specific tasks, particularly those specific to managing certain aspects of Active Directory.
My advice if you require Windows-based automation? Learn both. Even better, learn JScript and Perl. It isn't about the language; it's about getting the job done. Knowing both will help you do that.
Best,
Jason
http://www.wjgilmore.com/
-
Why not JScript?
2003-11-18 22:24:04 anonymous2 [View]
It's also pre-installed.
It supports prototype based OO.
Lots of people are already familiar with Javascript by using it in the web page setting.
And it's neither wordy like VBScript, nor cryptic as Perl. -
Why not JScript?
2003-11-23 07:29:16 anonymous2 [View]
In a WSH environment JScript support is limitted. Prototype-based inheritance just doesn't work, so this renders JScript useless. I haven't worked with WSH extensive, so I might be wrong. -
Why not JScript?
2003-12-31 02:19:07 anonymous2 [View]
Um, I don't see how JScript is useless? VBScript (and VB for that matter) only supports Object-Based programming, and through COM you cannot derive objects from one another anyhow. So, I don't see how lack of inheritence makes a difference when it comes to interfacing with COM libraries such as WMI, ADSI, Office, CDO, DAO, ADO, etc.
FYI, The newer JScript.NET (ECMAScript ver 4) supports true inheritence, but that's a different topic...
- Joaquin M. -
Why not JScript?
2003-12-01 13:44:39 anonymous2 [View]
You are wrong. JScript support in WSH is not limited. Prototype-based inheritance does work.
For WSH I tend to use .wsf files and mix JScript and Perl. I like using JScript's exception handling especially when using COM objects. If I need to spawn a process I prefer to use Perl to open a pipe instead of using the WshScriptExec object. -
Why not JScript?
2003-11-19 20:12:00 Robbie Allen |
[View]
I think one could make a very good argument for JScript. Especially with the integration into the .NET Framework, it is an attractive option. I'm not sure why it hasn't picked up as big of a following (from what I've seen) for doing sys admin scripting as VBScript.
I've done a lot with Javascript in HTML, but not in the WSH environment. One thing I may do to write companion JScript examples for all of the code in the AD Cookbook: http://www.rallenhome.com/books/adcookbook/code.html. Then I can look at the web logs and see what is the most popular. -
Why not JScript?
2003-11-20 10:05:45 anonymous2 [View]
I for one would appreciate more and better Jscript support. I've found some problems using VBScript in some places(specifically there are some nasty bugs in ActiveX scripts embedded in SQL Server). -
Python
2003-11-19 05:00:18 anonymous2 [View]
Python fits very well in the windows world (can talk to dll's, COM, etc) and has cleaner object orientation than perl. Python stresses clarity and simplicity, yet it is also a very powerful language. -
Python
2003-11-19 20:22:57 Robbie Allen |
[View]
I wondered if someone might ask why I left out Python :-) It is also a viable option (as is a few other languages). But I see even fewer Windows Sys Admins using it. If you have a Python background and need to write scripts for the Windows environment, then you probably shouldn't look at anything else. You can accomplish pretty much the same things with Python as you can Perl on Windows. But I still prefer Perl :-)
A good follow-on question to this article is Perl or Python? (in the Windows environment) If you knew both, would one be better than another? -
Python
2003-12-02 12:20:45 gjansen [View]
The interactive environment now supported by ActiveState is perhaps the best reason to go with Python in the Windows environment. (Certainly it compares favorably with running perl -e from a prompt). The COM interface is very straightforward to use, and wxWindows makes it easy to put up a good-looking GUI.
I still find that I use Perl almost exclusively in the Unix environment, simply because I had several years of Perl experience before I ever took up Python. -
Python
2003-11-19 10:45:07 anonymous2 [View]
"and has cleaner object orientation than perl"
But why would this matter in a scripting environment? No one is going to write a class for a 20-30 line utility script.
- Joe -
Python
2003-11-20 06:28:23 mahansen [View]
Code reuse would be the biggest reason to write a class for a utility script. Maybe you want to do something similar in another script, you can use that class in it.
Also, you'd be surprised how many 20-30 line utility scripts grow into monster apps. -
Python
2003-11-20 13:44:28 Robbie Allen |
[View]
I've written a 40,000 line web app in Perl which was loosely OO. Not to say it is a great example of Perl OO in action, but it can be done. -
Python
2004-01-01 17:18:12 anonymous2 [View]
Even a small set of perl 1-liners represent a powerful integration of near complete programs, so you can write a complete operating system in less than 40K lines of perl.
So, what exactly were you trying to attempt/achieve in those 40,000 lines of perl code ? I am extremely curious to know :-)
-
Python
2003-12-01 11:59:47 anonymous2 [View]
40,000 lines! My GOD man you should be ashamed of yourself! -
Python
2003-12-01 12:02:33 Robbie Allen |
[View]
:-) -
Python
2003-11-19 08:32:48 wjgilmore [View]
Agreed, Python does work quite well in the Windows environment. O'Reilly published a Python/Windows book, called "Python Programming on Win32" if I remember correctly. Another great book on Python is "Practical Python", by Magnus Hetland, published by Apress. (disclaimer: I was a tech editor).
Jason
http://www.wjgilmore.com/











This suggests perl needs to be installed on any machine a perl script needs to run on. Not so.
Easiest way around this is to install Activestate perl on ONE machine with all your favorite 3rd party modules and copy the "c:\perl" folder to a shared network location and call your scripts from a oneliner batch file like so.
\\server\perl\bin\perl.exe \\server\scripts\myscript.pl
or wrap it in a batch file like this:
@echo off
\\server\perl\bin\perl.exe -x %0 %*
:: the above command tells the perl interpreter to
:: strip off text before #!perl line and treat everything
:: afterward like a perl script!
goto endofperl
#!perl
print "this rocks, this portable script will \n";
print "run on any machine in the network. \n";
print "No perl install required on target machine \n";
__END__
:endofperl
Also, their are many ways to compile scripts into exe's for users and make mini-perl interpreters (like a 2 meg perl.exe interpreter) so you can send open-source scripts to other admins to edit/plagiarize. No need to install 50+ megs of perl on any machine + modules unless you are developing.
MSH thoughts:
MSH was supposed to be the bomb, but it's still in beta, needs to be installed on any machine it needs to run on (no friendly copying of "C:\Program Files\Microsoft Command Shell" to a network share), needs .NET 2.0 installed, only runs on XP/2003 and up (no NT/2000) and doesn’t look like it will make it into Vista.
MSH won't be common enough on platforms to be generally considered useful till post 2010.
And since msh is more of a language than a shell (a shell that glues small apps with switches together) we can look forward to all sorts of fun problems like what version we have and backwards compatibility issues... problems languages cause. (perl gets around this by having one installation point on the network)
Their was a perl based shell called PSH that is a lot like MSH. It allowed you to interactively load modules and do awesome stuff from the command line,(Python and Ruby can do this too), but neat as it was, it was never really useful...So much easier to make a quick 3-4 liner in your favorite IDE and launch it from their. (what's REALLY needed is a better IDE that has a embedded shell for output)
So, it's neat to iterate over files in an object oriented, interactive programming environment (MS's new shell) but the reality is, it's just not that useful and will have a limited audience.