Management Batch vs. VBScript vs. PowerShell Lead image: Lead Image © Andrey KOTKO, 123RF.com
Lead Image © Andrey KOTKO, 123RF.com
 

Logon scripts investigated

Scripting Competition

We compare the performance of batch, VBScript, and PowerShell commands with four standard tasks. By Thomas Wiefel

Logon scripts provide an important service when setting up a PC workstation: They create an individual workplace environment for each employee based on the employee's logon context. On Windows XP, scripting was limited to batch files and VBScripts; however, PowerShell has elevated the scripting game since Windows 7.

Is PowerShell really so much better, though? To try and find some clarity in this matter, I put the three technologies – batch (statements and binaries interpreted by cmd.exe), VBScript (Visual Basic Script Edition, processed by Wscript.exe or cscript.exe), and PowerShell (version 3; console with additional script engine for PS1 files) – to the test. In doing so, I consider:

Objective and Scenario

Logon script targets can be divided roughly into two areas: infrastructure and local system. Infrastructural objectives could be managing shares, particularly mapping network drives, or connecting a network printer and setting the default printer. For local systems, it might be necessary to run programs, change a registry key, or create a link.

The typical tasks I will give the three Microsoft scripting engines in this test involve mapping shares, adding a network printer, running a file, and changing the registry. Additionally, I expect to see output in the event of an error.

Mapping Shares

Connecting to shares on a server is a standard task in setting up a desktop. The DOCS share on server SRV will be mapped as drive M. To simplify matters, I am omitting the transfer of user information for securing rights for this action.

Batch: The batch command for this action is:

net use m: \\SRV\DOCS

The net.exe file handles this command. The mixture of command interpreter access and commands is typical of batch files.

VBScript: The VBScript command is:

Set ObjNet = Wscript.CreateObject("Wscript.Network")
ObjNet.MapNetworkDrive("m:","\\SRV\DOCS")

A VBScript logon script only provides the control constructs such as loops, branches, and so on. The actual functionality is in a collection of component object model (COM) objects (standard for software development at Microsoft) – in particular, the Windows Script Host (WSH) run-time library.

In this example, I create an object based on the WScript.Network class in order to then use the MapNetworkDrive method.

PowerShell: The PowerShell command is:

New-PsDrive -name m -Root \\SRV\DOCS \
   -PsProvider FileSystem -persist

PowerShell uses the cmdlet command type. Simplified, cmdlets can be understood as an extension of .NET types. The <verb>-<noun> structure makes usage very intuitive. Here, the New action is connected with the PsDrive target.

Printer Management

The second step involves sharing a network printer with the user. The server has the familiar name SRV, and the shared printer is referred to as PP. I also want this printer to be the default printer.

Batch: First up is the batch command:

Rundll32 printui.dll,PrintUIEntry /in /n /Y \\SRV\PP

The Rundll32.exe application steps into the breach for the weak internal commands of command.com. Here, it defines the printer as a network printer (/in) with a name (/n) in the form of \\<server>\<sharing name>. The default printer property is set with the /Y option.

VBScript: Visual Basic uses the following command chain for printer configuration:

Set ObjNet = Wscript.CreateObject("Wscript.Network")
ObjNet.AddWindowsPrinterConnection("\\SRV\PP")

This is the second WScript.Network type method. VBScript proves to rely very heavily on COM. Later, I will look at whether this is an advantage or disadvantage.

The same object can also carry out part two of the task,

ObjNet.SetDefaultPrinter("\\SRV\PP")

which defines the printer as the default.

PowerShell: PowerShell is more flexible with this command:

$pr = get-WmiObject -Class "win32_Printer"
$pr.AddWindowsPrinterConnection("\\SRV\PP")

It can access, among other things, .NET types and WMI classes. The new printer receives the default flag,

$default = get-wmiObject -Class win32_Printer \
   -Filter "name = 'PP'"
$default.SetDefaultPrinter()

which identifies it in the list of available printers. This is somewhat elaborate, but meaningful.

Registry Extension

So far, all three scripting languages have proven their general suitability in the area of infrastructure. Now I want to create a key in the registry for the local system and equip it with a pair of values. I will be creating the DATA key under HKEY_LOCAL_MACHINE\SOFTWARE and defining the Remote with a value of 1. The second task for the three scripting methods is to start the C:\tools\clean.exe file. If an error occurs, I want to inform the user that the application could not be launched.

Batch: The batch file starts with

Reg ADD HKLM\Software\Data
The third executable file requires space:
Reg ADD HKLM\Software\Data /v Remote /t REG_SZ /d 1

As simple as the statement is, the fact that a general statement cannot be made on the binary's availability in various operating systems makes the use of many binaries problematic.

VBScript: In comparison, the VBScript approach to extending the registry is as follows:

Set ObjShell = Wscript.CreateObject("Wscript.Shell")
$NewKey = ObjShell.RegWrite\
("HKLM\Software\DATA","remote","1","Reg_SZ")

For this purpose, I make use of the other large object in the Wscript run time: the Wscript.Shell object. Using the RegWrite method, the key and value are stored using just one statement.

PowerShell: How does PowerShell set the default? In principle, PowerShell uses the same commands for editing the registry as for the filesystem:

New-Item -path HKLM:\Software\DATA -itemType Directory

PowerShell considers all containers to be drives, whether it is an SQL database server, an Active Directory, a registry, or a filesystem.

New-ItemProperty -Path HKLM:\Software\DATA \
                   -Name remote -value 1 -type string

Again, the New action is linked to an element. The corresponding noun here is ItemProperty, because the value pair is a property.

Starting a Program with Feedback

The final test comparing the three candidates involves launching an application with error handling.

Batch: The veteran approaches this problem as follows:

C:\tools\clean.exe
If errorlevel 1 goto error
:error
Clean.exe could not be started

The expression errorlevel 1 checks to see whether the return value for the previous statement is equal to or greater than 1. A query if errorlevel 0 goto success would fail because the error code 1 would be included. The type of error (e.g., missing permissions or non-existent file) is not specified.

VBScript: VBScript, however, uses:

On Error Resume Next
Set ObjShell = Wscript.CreateObject("Wscript.Shell")
ObjShell.Run "C:\tools\clean.exe"
If Err.Number <> 0 THEN
Wscript.Echo "An error occurred!"
On Error Goto 0

The line On Error Resume Next hands over error handling to the script. If a statement triggers an exception, it generates an error code, which can be negative; therefore the test is "not equal to zero."

PowerShell: Finally, the Windows PowerShell command is:

$ErrorActionPreference = "stop"
Try {Invoke-item "C:\tools\clean.exe"}
Catch [System.IO.IOException]{"Error in processing, is file present?"}
Catch {"Error running clean.exe"}

PowerShell is in a different league from batch or VBScript with regard to error handling.

The construct TryCatch allows exceptions to be caught and handled at the statement level, and you even have the possibility of responding to specific errors, such as missing permissions and the like.

Conclusions

The applications used by batch files, such as net.exe, for example, were essentially developed for Windows NT. One of the problems is its inability to adapt to the scripting needs that have arisen since it was created. Ultimately, when using batch files, you need to predict support in the future for each component, and sometimes even for current operating systems.

A consistent syntax model is not possible because of this fragmentation. Each command implements the way it transfers parameters differently. The documentation also suffers from this heterogeneous structure, with no uniform help system.

The batch file is restricted to text as a format for input/output. Native support for XML, CSV, and HTML is not known for this technology. Objects are not implemented, either. However, processing speed is a positive.

VBScript can boast the support of object models COM and WMI. As a result, the development of logon scripts is much more stringent.

You can also address installed applications such as Office via this interface, which provides flexibility in I/O routines, such as redirecting output to an Excel file. Unfortunately, the COM object model is one of the slowest in the universe. Complex tasks can thus try your patience. VBScript additionally cannot beat batch in terms of error handling. However, the documentation of the core components is well done.

The current flagship among administrative tools overcomes all the previously described shortcomings of the veterans batch and VBScript (see the "Advantages of PowerShell" box). Windows PowerShell supports all object models, its scripts have a tremendous range of functions and are assured of a good future, and the internal help is perfectly integrated (Table 1). Syntax, parameters, and examples can be accessed for each command using get-help, and a very good editor with debugging facilities, the Integrated Scripting Environment (ISE), is also available.

Tabelle 1: Logon Scripts Compared

Technology

Object Models

Error Handling

Typed Errors

Documentation

Batch

Net.exe Rundll32 reg.exe

errorlevel

External

VBScript

WScript run time

COM WMI

Error object

WSH documentation

PowerShell

Cmdlets WMI

WMI COM/DCOM .NET

TryCatch

X

get-help Completion Syntax completion ISE

Error handling with the support of error types for standard language is state of the art. XML, CSV, HTML, JSON, and text are available as output and input formats. Even sending email is not problematic.