Implementing programming constructs in PowerShell
Since this is a book on mastering PowerCLI, I will assume that you already know the basics of the language. For example, how variables are declared in PowerShell and various restrictions on them. So, in this section, I am going to provide a short refresher on the different programming constructs and how they are implemented in PowerShell. I will deliberately not go into much detail. For details, check out https://technet.microsoft.com/en-us/magazine/2007.03.powershell.aspx.
In any programming language, the first thing that you need to learn about is the variables. Declaring a variable in PowerShell is pretty easy and straightforward; simply, start the variable name with a $
sign. For example, run the following code:
PS C:\> $newVariable = 10 PS C:\> $dirList = Dir | Select Name
Note that at the time of variable creation, there is no need to mention the variable type.
You can also use the following cmdlets to create different types of variable:
New-Variable
Get-Variable
Set-Variable
Clear-Variable
Remove-Variable
Best practice for variables is to initialize them properly. If they are not initialized properly, you can have unexpected results at unexpected places, leading to many errors. So, you can use Set-Strictmode
in your script so that it can catch any uninitialized variables and thus remove any errors creeping in due to this. For details, check out https://technet.microsoft.com/en-us/library/hh849692.aspx.
When we started programming, we started with flowcharts, then moved on to pseudo code, and then, finally, implemented the pseudo code in any programming language of our choice. But in all this, the basic building blocks were the same. Actually, when we write any code in any programming language, the basic logic always remains the same; only the implementation of those basic building blocks in that particular language differs. For example, when we greet someone in English, we say "Hello" but the same in Hindi is "Namaste". So, the purpose of greeting remains the same and the effect is also the same. The only difference is that depending on the language and understanding, the words change.
Similarly, the building blocks of any logic can be categorized as follows:
- Conditional logic
- Conditional logic using loops
Now, let's take a look at how these two logics are implemented in PowerShell.
Conditional logic
In PowerShell, we have if
, elseif
, else
and switch
to use as conditional logic. Also, to use these logics properly, we need some comparison or logical operators. The comparison and logical operators available in PowerShell are as follows:
Comparison operators:
Operator |
Description |
---|---|
|
Equal to |
|
Not equal to |
|
Less than |
|
Greater than |
|
Less than or equal to |
|
Greater than or equal to |
Logical operators:
Operator |
Description |
---|---|
-not |
Logical Not or negate |
! |
Logical Not |
-and |
Logical AND |
-or |
Logical OR |
The syntax for the if
statement is as follows:
If (condition) { Script Block} Elseif (condition) { Script Block} Else { Script Block}
In the preceding statement, both elseif
and else
are optional. The "condition" is the logic that decides whether the "script block" will be executed or not. If the condition is true, then the script block is executed; otherwise, it is not. A simple example is as follows:
if ($a-gt$b) { Write-Host "$a is bigger than $b"} elseif ($a-lt$b) { Write-Host "$a is less than $b"} else { Write-Host " Both $a and $b are equal"}
The preceding example compares the two variables $a
and $b
and depending on their respective values, decides whether $a
is greater than, less than, or equal to $b
.
The syntax for the Switch
statement in PowerShell is as follows:
Switch (value) { Pattern 1 {Script Block} Pattern 2 {Script Block} Pattern n {Script Block} Default {Script Block} }
If any one of the patterns matches the value, then the respective Script Block
is executed. If none of them matches, then the Script Block
respective for Default
is executed.
The Switch
statement is very useful for replacing long if {}
, elseif {}
, elseif {}
or else {}
blocks. Also, it is very useful for providing a selection of menu items.
One important point to note is that even if a match is found, the remaining patterns are still checked, and if any other pattern matches, then that script block is also executed. For examples of the Switch
case and more details, check out https://technet.microsoft.com/en-us/library/ff730937.aspx.
Conditional logic using loops
In PowerShell, you have the following conditional logic loops:
do while
while
do until
for
Foreach
Foreach-Object
The syntax for do while
is as follows:
do { Script Block }while (condition)
The syntax for the while
loop is as follows:
While (condition) { Script Block}
The following example shows the preceding while
loop. Say, we want to add the numbers 1
through 10
.
The do while
implementation is as follows:
$sum = 0 $i = 1 do { $sum = $sum + $i $i++ }while( $i –le 10) $sum
The while
implementation is as follows
$sum = 0 $i = 1 while($i -le 10) { $sum = $sum + $i $i++ } $sum
In both the preceding cases, the script block is executed until the condition is true
. The main difference is that, in the case of do while
, the script block is executed at least once whether the condition is true
or false
, as the script block is executed first and then the condition is checked. In the case of the while
loop, the condition is checked first and then the script block is executed only if the condition is true
.
The syntax for the do until
loop is as follows:
do { Script Block }until (condition)
The main difference between do until
and the preceding two statements is that, logically, do until
is the opposite of do while
. This is the script block is that is run until the time the condition is false
. The moment it becomes true
, the loop is terminated.
The syntax for the for
loop is as follows:
for (initialization; condition; repeat) {code block}
The typical use case of a for
loop is when you want to run a loop a specified number of times. To write the preceding example in a for
loop, we will write it in the following manner:
For($i=0, $sum=0; $i –le 10; $i++) { $sum = $sum + $i } $sum
The syntax for the foreach
loop is as follows:
foreach ($<item> in $<collection>) {code block}
The purpose of the foreach
statement is to step through (iterate) a series of values in a collection of items. Note the following example. Here, we are adding each number from 1
to 10
using the foreach
loop:
# Initialize the variable $sum $sum = 0 # foreach statement starts foreach ($i in 1..10) { # Adding value of variable $i to the total $sum $sum = $sum + $i } # foreach loop ends # showing the value of variable $sum $sum
Logically, foreach
and Foreach-Object
do similar tasks, and sometimes this can create confusion between the two. Both of them are used to iterate through collections and perform an action against each item in the collection. In fact, foreach
is an alias for Foreach-Object
.
The difference between Foreach and Foreach-object
When we use Foreach
in the middle of a pipeline, that is, when we pipe into Foreach
, it is used as an alias for Foreach-Object
, but when used at the beginning of the line, it is used as a PowerShell statement.
Also, the main difference between foreach
and Foreach-Object
is that when Foreach-Object
is used, it executes the statement body as soon as the object is created, but when foreach
is used, all the objects are collected first and then the statement body is executed.
So, when we are using foreach
, we need to make sure that there is enough memory space available to hold all the objects.
Having said that due to optimizations in foreach
, foreach
will run much faster than the Foreach-Object
statement, so the decision again boils down to that age-old question of performance versus space.
So, depending on the program that you are writing, you need to choose wisely between these two.