Unary operators work on a single operand. PowerShell provides unary operators and through this article, we are going to discuss them.
The ++
operator – Post & pre-increment operator
The unary operator ‘++’ will increment the value of the operand by 1. It has two forms, post & pre-increment forms. When the unary operator ‘++’ is mentioned in front of the operand, we call it a pre-increment operator.
PS C:\> $var = 1 PS C:\> ++$var PS C:\> $var 2
When the unary operator ‘++’ is mentioned after the operand, we call it a post-increment operator.
PS C:\> $var = 1 PS C:\> Write-Output ($var++) 1
Have you observed the result? Why $var
variable’s value displayed as 1? There is a difference between pre & post increment operators. When we use the pre-increment operator, the value will increment first and then will evaluate the expression; but, in the case of the post-increment operator, the expression will evaluate first, and then the value will increment later. Hence you are seeing the above result.
PS C:\> $var = 1 PS C:\> Write-Output ($var++) 1 PS C:\> Write-Output (++$var) 3
Depending on the need you can use either post or pre-increment operator.
The --
operator – Post & pre-decrement operator
The unary operator ‘–‘ will decrement the value of the operand by 1. The unary operator ‘–‘ has two forms; post & pre-decrement forms.
Similar to unary ‘–‘ operators; when we use the post-decrement unary operator the expression will evaluate first and then will decrement the value of the operand. Whereas with a pre-decrement unary operator the value will decrement first, and the expression will evaluate after that.
Here are the examples to understand how the unary decrement operator works;
PS C:\> $var = 2 PS C:\> echo ($var--) 2 PS C:\> echo (--$var) 0
[..] David