Counter in PowerShell
In programming, counters are used to track what is needed to be counted within your program. Usually, this is a numeric type variable that is initialized to
There are several approaches to increment a counter within a program. In this article, we will be focusing on different approaches to implementing counters in PowerShell.
Basic Counter in PowerShell
The basic way to implement a counter is by declaring a variable and initializing it to
0, as shown in the following.
$counter = 0
Let’s print the
$counter variable value to the PowerShell command window.
We can use two methods to increment the value of the
$counter variable. One traditional way is to add one to the
$counter and re-assign the result to the
$counter = $counter + 1
Another approach is to use the increment (
Let’s print the value of the
$counter variable, which must be
As expected, the value of the
$counter variable is
There are two ways of incrementing a counter variable.
Let’s understand the difference between the two using an example.
Post-Increment Operator in PowerShell
Usually, the post-increment increments the variable’s value after executing an expression where the post-increment is being used. We can easily understand it with the following example.
Let’s first declare a variable called
$countVar and assign
0 to it.
$countVar = 0 Write-Host $countVar
Next, we will use the post-increment to increment the value of the
$counterHolder = $countVar++ Write-Host $counterHolder
As you can see, the
$counterHolder variable holds
0, which means the
$countVar++ didn’t increment within that expression. But the actual value of the
$countVar should have been incremented. Let’s print the
$countVar variable value.
Pre-Increment Operator in PowerShell
The pre-increment operator is used to increment a variable’s value before using it in an expression. Let’s understand this with the following example.
First, we will declare a variable called
$preIncrVar and initialize it to
$preIncrVar = 0 Write-Host $preIncrVar
Let’s use the pre-increment operator as follows.
$preIncrVarHolder = ++$preIncrVar Write-Host $preIncrVarHolder
As expected, the
$preIncrVarHolder variable’s value is
1, which means the pre-increment operator increments the value of the
$preIncrVar variable within the expression that is being used. These approaches can be used in the
do...while loops in PowerShell.