Guy’s Scripting Ezine 125 – PowerShell, Scripting for Everyone

Guy’s Scripting Ezine 125 – PowerShell, Scripting for Everyone

 ♣

This Week’s Secret

I wish that Windows PowerShell was around when I first learned how to write computer scripts.  PowerShell is simply the easiest scripting language that I have ever used.  Yet it is potent and as you learn, so you get maximum reward for your effort.  PowerShell’s status as Microsoft’s flagship script language must ensure that it has a secure future, even more impressively, I have yet to hear anything bad about PowerShell.

When I first started scripting I felt guilty when I copied other people’s scripts, but talking to scripters, I soon realized that everyone regards copy and paste as normal behaviour for learning to write code.

With the power of the internet you can find a beautiful script to perform almost any task.  However, the paradox is the better and cleverer the script, the harder it is to understand and thus it becomes difficult to modify the script to one’s specific task. 

This is why seek to create only simple scripts.  I try to design scripts that are so easy that complete beginners not only understand them, but also can adapt them for their own tasks.  My ultimate goal is to create a library of scriplets so that readers can bolt together several individual scripts and thus produce one really powerful script to solve their problem.

This Week’s Mission

This week my mission is to persuade those with little or no scripting knowledge to give Windows PowerShell a chance.  Rather than choosing a highfaluting active directory example, I have chosen the simple task of finding a file.  Now we could call for Search in Windows Explorer or issue the old DIR command in dos.  But the reason I have chosen PowerShell is that it can add extra touches which are not possible with existing methods.  For example: Find all files that contain the phrase ‘Operating System’*  and then display a list of these files sorted in order of the greatest incidence of the string ‘Operating System’.

* Naturally, you could substitute your own string value

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Example 1 – To find all files with .doc extension

As usual, we are going to start slowly and build on success.  Let us begin by simply displaying all the files in a named path which have the .doc extension.

Pre-requisite

  1. Check the path and then amend e:\ files in my code, with a local folder that contains word documents.

get-childitem e:\files -recurse -include *.doc

Learning Points

Note 1:  PowerShell constantly and consistently uses the construction, verb -dash- object.  For example, get-childitem and select-string.

Note 2:  The dash or hyphen often fools beginners.  There are two rules to note for this dash.  Firstly, in the verb-object pairing there is never a space next to the dash.  Get-childitem is correct, whereas get  -childitem will result in an error message.

Secondly, PowerShell’s word for a switch or modifier is a parameter.  In Example 2 -recurse is a parameter, which recursively drills down to sub-directories.  Learn by heart that the sequence for parameters is as follows, space dash parameter, for example, -include.

Example 2 – To display only files which contain the word ‘Computer’.

Pre-requisites

  1. Find the path referenced and then amend e:\ files to a suitable folder on your local disk.
  2. Decide on the value for the string, do you want to find ‘Computer’?  If not choose your own search string.

get-childitem e:\files -recurse -include *.doc | select-string ‘Computer’ |group-object filename 

Note 1:  It is often useful to filter the output of a Windows PowerShell command; it also saves code if you can join two commands together.  For example, find all documents, filter for the word computer and group the results by the filename.  When you need to join commands in this way, PowerShell supplies the Pipe symbol | (or ¦).  

Be on your guard for confusion caused by the two ways of displaying this symbol.  To be crystal clear, PowerShell requires the symbol displayed when hold down the Left Alt key and type 124 on the numeric keypad.  You should now have ASCII 124 = |.  The confusion arises because in the PowerShell interface it looks like this, ¦.  See more on Get-ChildItem parameters.

Example 3 – To order results by the frequency of the word in the search string

Script problem.  We want to add the sort-object instruction, however, the command string is getting too long.  Solution, let us use PowerShell’s abbreviations, for example gci is shorter than get-childitem. Also we can shorten -recurse to -r and -include to -i.

Pre-requisites

  1. Check path, amend e:\ files in my code
  2. Decide on the value for the string, do you want to find ‘Computer’.  If not choose your own search string.

gci e:\files -r -i *.doc | select-string ‘Computer’ |group filename |sort count -desc

Note 1:  Group-object and sort-object can be truncated to Group and Sort.  However, if we omit the string from select-string you get an unexpected result. 

Note 2: If you only have one word in your string you can omit the speech marks around ‘Computer’, but as you many need to amend my code and search for a phrase, I left the speech marks in my script.

Note 3:  I also tried to shorten -descending to -d, but that confused PowerShell.  The rule for shortening parameters is that they must still be unique.  -desc, could only means -descending, whereas -d is ambiguous, it could also mean -debug, consequently, PowerShell terminates the command and warns us with a very readable message.  Incidentally, help is something that you will enjoy with PowerShell, no obscure error code 8007020B message, instead a useful explanation of what went wrong – if only we bother to read such messages!

Guy’s Challenge

Make use of PowerShell’s built-in help at every opportunity.  The key is to start with get-help, or plain help, for example:

  1. get-help childitem   Alternatively try plain: help gci
  2. get-help select-string
  3. Even get-help sort has valuable information on parameters, plus examples.

Summary of Windows PowerShell

I cannot help noticing how much shorter the PowerShell commands are compared with VBScript or other scripting languages.  While these are only beginner scripts, you will find that even complex tasks can be achieved with relatively few lines of PowerShell code.  PowerShell is the scripting language of the future, enjoy learning it today.

If you like this page then please share it with your friends

 


See more Windows PowerShell tutorials

PShell Home   • Introduction   • Dreams   • 3 Key Commands   • PowerShell Help About   • Get-Help

PowerShell v 3.0   • Set-ExecutionPolicy   • Get-Command   • Cmdlet scripts   • Import-Module

PowerShell Version Check   • Backtick   • PowerShell examples   • PowerShell ISE   • Get-Member

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.