Powershell tutorial. The For Statement

This week’s lesson builds on last weeks tutorial but introduces the For statement. The For statement uses a counting loop that processes and continues through a collection as long as the condition equals true. Similar to If statements, the for statement includes a conditional code block and a script block. However you will see that the conditional code block is far more complex.

Lets begin with an example;

for ($a = 1; $a -le 5; $a++) {$a}

We start with the keyword for, followed by the conditional code block ($a = 1; $a -le 5; $a++) {$a}. The conditional block is made of 3 parts separated by semicolons. Part one ($a = 1) sets the $a variable with the value of 1. This $a variable provides the starting value for the other block elements. Part two ($a -le 5) is the actual condition which states that the value of $a must be less than 5 to equal true. Part three ($a++) increments the $a variable by 1 after each pass of the loop is made. In this way the statement will continue to step through the collection so long as the value of $a is less than or equal to 5. Once $a equals 6 the for statement will end.

$files = dir c:archivedfiles*.txt
if ($files.count -ne $null)
{
for ($i =0; $i -lt $files.count; $i++)
{
$files[$i].name + ” = ” +
$files[$i}.length + ” bytes”
}
write-host
}
elseif ($files -ne $null `
-and $files.count -eq $null)
{
$files.name + “=” +
$files.length + “bytes”
write-host
}
else
{
“no test files in this folder.”
write-host
}

In this code we are assuming that we don’t know the number of elements that will be in the collection. First the code begins by storing a collection of text files in the $files variable. The if statement uses the $files variable and its count property ($files.count) to check the total file count. If there is only one file in the collection, then PowerShell returns an object that has a scalar value. If no files are found, then PowerShell does not return an object. As a result a null value is received if you try to call the count property, which is why we are using it as a condition in the if statement. When $files.count returns a null value, the elseif clause “elseif ($files -ne $null `…..”checks for the condition of there being only one file. If this condition is not met then there are no files and the else clause “else { “no text files in this folder.”….. is run. When $files.count does not return a null value then there must be at least two files and the embedded for statement’s conditional code block uses the count property to determine the exact number of files in the collection. So long as $i is less than the number of elements, the condition equals true.

Leave a Reply