Tuesday, 13 August 2013

Windows PowerShell for Developers #2: The Bad Old Days

In the first installment of this blog I looked at how nice it would be if we could make our software development chores easier by automating tedious tasks.

Before we plough on with the main subject of this blog, which is bringing the awesomeness of Windows PowerShell  to our everyday work experience, let's look at the way things used to be done (and still are, to some extent) and how we might improve upon them.

The Bad Old Days:  BATs in the Belfry.

All of us have at some point come across a Windows Batch File.  Batch files are the simplest kind of scripting automation you'll come across in Windows and end in '.BAT'.   Do a Windows Search for '*.BAT' and see what it unearths.
Batch files stem back to  the days of MS-DOS, which was driven primarily by typing commands in at the command line. (Many of you reading this blog will never have touched an MS-DOS machine).  Microsoft Windows first drew breath as a graphical shell over MS-DOS, so batch files continued to be a feature of the operating system for many years.  AUTOEXEC.BAT is probably the most well-know batch file of all.  This file contained a series of commands that were run just after the machine had started up fully, and just before it was ready to accept commands from the user.  If you cut your professional teeth on DOS systems, then delving around in the innards of this file was unavoidable.

The contents of a typical AUTOEXEC.BAT might be:

@ECHO OFF
PROMPT $P$G
PATH C:\DOS;C:\WINDOWS
SET TEMP=C:\TEMP
SET BLASTER=A220 I7 D1 T2
LH SMARTDRV.EXE
LH DOSKEY
LH MOUSE.COM /Y
WIN


Most modern computer users would be totally flummoxed by this, but it's really pretty simple.  Each command is on its own line and would normally have been typed in by the user.  The commands set up various operating parameters of the system, saving the user from having to do it.

Users could write and save their own batch files to perform complex commands.  The main drawback with using them to handle complexity was that the batch language itself (which didn't have a name) didn't really support complex code.  Branching IF THEN ELSE , and loop structures, were not supported and so scripters had to resort to horrible GOTO statements.

Things improved somewhat when Windows became Windows NT.  Out went the old 16-bit command processor and in came the new 32-bit CMD.EXE.  The user experience was pretty similar, except that CMD.EXE ran in a window on the desktop, but the old commands still worked and some 'syntactic sugar' was sprinkled over the command language to make it more palatable.

VBScript and the Windows Script Host

VBScript was a drastically cut down version of Visual Basic initially intended to be used within web pages,  but was touted by Microsoft as a valid alternative to writing batch files. VBScript files could be run from the command prompt using the cscript command, and from the Windows desktop using wscript.exe.  VBScript doesn't really work unless it runs inside another environment, such as the browser or the Windows Script Host.

Where VBScript really came into its own was when managing  advanced features of Windows itself.  The following script shuts down any instance of Notepad.exe:

'Terminate all processes involving the name <strProcessToKill
Option Explicit
Dim strComputer, strProcessToKill, objWMIService, colProcess, objProcess
 
strComputer = "."
strProcessToKill = "notepad.exe"
Set objWMIService = GetObject("winmgmts:" _ 
   & "{impersonationLevel=impersonate}!\\" _ 
   & strComputer _ 
   & "\root\cimv2") 
Set colProcess = objWMIService.ExecQuery _
   ("Select * from Win32_Process Where Name = '" & strProcessToKill & "'")
For Each objProcess in colProcess
   msgbox "... terminating " & objProcess.Name
   objProcess.Terminate()
Next

VBScript is still widely used by Windows system administrators.  However, it lacks a certain degree of flexibility compared to the batch files.  You can't sit down and type VBScript commands in and get them executed a line at a time.  VBScript has to reside in a .vbs file.  It's also very verbose.

What was needed was something that combined the slickness of batch commands with the power of VBScript.

PowerShell.

PowerShell is the most advance scripting environment produced for Windows.  Its name gives away the philosophy behind its motivations.  The term 'shell' is a Unix concept.  The originators of Unix saw the operating system rather like a nut:  a 'kernel' would run all the basic operations of any operating system, while a 'shell' sat around it and protected these from the outside world.  The only way you could directly get the kernel to do something was to go through the shell.

Unix shells supported a surprisingly sophisticated command-line interface.  Probably the first shell that most Unix users would come across was the Bourne shell.  This was really a very sophisticated beast for the day:  it had advanced features like pipes (which used the '|' symbol to chain commands together) which could direct the output from one command directly into the next one in the pipeline.  (Think of it as the computing equivalent of the 'Human Centipede'!)

PowerShell does away with the syntactic legacy of VBScript and takes much of its inspiration from the Unix world.  It builds upon the Unix way of doing things from the bottom up.  It also allows pipes, for example, but instead of using them to shuttle text between commands, fully fledged .NET objects are exchanged.  It's this underlying architecture that gives PowerShell so much of its power.

Learning PowerShell

If you want to learn PowerShell then there are some excellent tutorials available.  I wouldn't suggest spending too much time on these, however, as I'm going to work through case studies and examples that I encounter in my job.  I learned PS on the hop, and if you can write software in Visual Studio then so can you.

I'll get onto a real life application of PowerShell to developing software in my next posting.

No comments:

Post a Comment