Breaking Down a PowerShell Script

The best way to learn programming and how things work is to try to build it and break it over and over again. It's the one thing that we actually have control over! The moment you break a program, fix it and fix it to be ten times better. To do so, understanding how the script is broken down and how to fix it is key. In this tutorial, you will learn how to break down a PowerShell script.

Setup

If you have not already done so, click on your start button and type in Windows PowerShell. Go ahead select and open Windows PSH (ISE).

Step one.

Let's go ahead and make a script real quick. The script will basically be a modification of the DIR command. It reads some command line parameter which should specify the path to a folder on your system. It lists contents of the folder like DIR, except you are going to display a color-coded output using red text for files and green text for directories.

Copy and paste the following code:


Example

if  ($args.count –ne 1) {
                Write-Host "Missing Parameter!" –foregroundcolor "Red"
                Exit
}
 
$folderPath = $args[0]
Write-Host ("Directory listing of " + $folderpath)
 
# Process each item in the directory
foreach ($i in get-childitem $folderpath) {
                if ($i.mode.substring(0,1) –eq "d") {
                                Write-Host $i.name –foregroundcolor "Blue"
                } else {
                                Write-Host $i.name –foregroundcolor "Green"
                }
}
     

Copy and Try it

Save this on your system as mydir.ps1.

In your PSH window, go ahead and run:

Example

C:\scripts\mydir.ps1 C:\
     

Copy and Try it

This particular command lists out the contents of the root of the C: drive using your new script. On my system I have C:\scripts, however you can change the path to where ever you save your scripts.

If the script is in a place with one or more spaces such as C: \, then you must start off the path with an ampersand and then enclose the path with single quotes. If you are already in a directory where you saved your scripts and you try running it by entering just the script name (such as mydir.ps1 C: \), PSH states it isn't a recognized Cmdlet, function, program or script file.

To run a command that is in a directory you're currently in, you have to prefix it with ".\", a period before a backslash like the following:

Example

	
. \mydir.ps1 C:\

     

Copy and Try it

Remember in order to run this script, you need to set your execution policy to RemoteSigned at least, otherwise, PSH will not permit you to run your script.

Step two.

Now to break down your script. We will be dealing with the first part of the code which handles command line arguments:

Example



if  ($args.count –ne 1) {
                Write-Host "Missing Parameter!" –foregroundcolor "Red"
                Exit
}
$folderPath = $args[0]
     

Copy and Try it

The first line checks whether the number of command line arguments is not equal to 1 because you need to have the path of the folder specified as the first argument. If not you won't be able to do anything. If there isn't exactly one argument, PSH outputs Missing Parameter. If there is exactly one argument, PSH takes the argument, stores it in the $folderPath available and then displays Directory listing of following by the name of the folder as a heading for the rest of the output:

Example


# Process each item in the directory
 
foreach ($i in get-childitem $folderpath) {
                if ($i.mode.substring(0,1) –eq "d") {
                                Write-Host $i.name –foregroundcolor "Blue"
                } else {
                                Write-Host $i.name –foregroundcolor "Green"
                }
}
    

Copy and Try it

This section of code is a loop. The line with the pound mark, (#), is actually a comment. That is how comments are carried out in PowerShell. When one implements a hash or pound mark, it tells PowerShell to ignore that one line. Same goes for commenting out code. If you want a particular line commented out, simply place an "#" in front of it.

The next line which begins with for each, creates a loop. It states "for each object in the parenthesis, perform the action that has been defined inside the curly braces". That information within the parenthesis is usually referred to as the condition for the loop and in this particular situation, all objects returned from the running Get-ChildItem against the given folder path.

The Get-ChildItem command grabs a list of items in the specified path. In this case, it's the path the user of the script provides as a command line parameter. Every repetition of the loop brings back one item, which it stores temporarily in the $i variable. Inside the loop it uses $i to refer to the single object returned by this particular repetition of the loop. Every item in a folder contains a set of properties such as its Name, Length, LastWriteTime and Mode. The mode being whether that item is directory, archive, read-only, hidden or system. When you retrieve the value of the property, Mode, its returned as a sequence of five characters (darhs) and any attribute that isn't set is instead replaced with a dash.

Now you know that if you query the mode property and the item is an archive, the first character in this value is (a). That's what you do in your first script, you take the first character in the mode property and check to see if it's a, if so, then the object is an archive, you use the Write-Host command to display the name using blue as the foreground color.

Remarks last but not least…

That's the break down on the script we made. We will cover loops further as we go along in our tutorials. Join us next time for more PowerShell tutorials! Till then