A unary operator acts on a single operand, unlike binary operators which require two. It can produce a new value, modify a variable in-place, invert a boolean condition, or toggle numeric signs. Because unary operators have high precedence in the PowerShell evaluation engine, they execute before binary arithmetic or relational expressions.
PowerShell provides unary operators for incrementing/decrementing values, flipping the sign of a number, and negating a boolean expression.
Increment and Decrement Operators (++ and --)
The increment (++) and decrement (--) operators add or subtract 1 from a numeric variable's current value. They can be positioned either before the variable (prefix) or after the variable (postfix), which determines when the modification occurs relative to expression evaluation.
| Operator | Syntax | Description |
|---|---|---|
| Prefix Increment | ++$var |
Increments $var by 1 before the expression is evaluated. |
| Postfix Increment | $var++ |
Returns the current value of $var, then increments $var by 1. |
| Prefix Decrement | --$var |
Decrements $var by 1 before the expression is evaluated. |
| Postfix Decrement | $var-- |
Returns the current value of $var, then decrements $var by 1. |
Basic Examples
$count = 5
$count++
Write-Output $count6$count = 5
$count--
Write-Output $count4Both operators can also be used as a prefix, applying the change before the value is used in an expression:
$count = 5
Write-Output (++$count)
Write-Output $count6
6Prefix vs. Postfix Evaluation
$counterA = 5
$resultA = $counterA++
$counterB = 5
$resultB = ++$counterB
[PSCustomObject]@{
Type = "Postfix ($counter++)"
Returned = $resultA
FinalValue = $counterA
}
[PSCustomObject]@{
Type = "Prefix (++$counter)"
Returned = $resultB
FinalValue = $counterB
}where:
$counterA++assigns the initial value (5) to$resultA, then updates$counterAto6.++$counterBincrements$counterBto6immediately, then assigns6to$resultB.
pwsh ./increment-decrement.ps1Type Returned FinalValue
---- -------- ----------
Postfix ($counter++) 5 6
Prefix (++$counter) 6 6Unary Plus and Unary Minus (+ and -)
The unary plus and minus operators precede a single numeric expression to set its polarity or force numeric type conversion.
Unary Minus (-)
The unary minus operator negates the value of a number, turning positive numbers negative and negative numbers positive:
$temperature = 15
-$temperature
$offset = -50
-$offset-15
50$value = 10
$negative = -$value
Write-Output $negative-10$negative = -10
$positive = -$negative
Write-Output $positive10where:
- Applying
-to an already negative value flips it back to positive. - The unary minus is distinct from the subtraction operator, context determines which one PowerShell applies, based on whether one or two operands are present.
Unary Plus (+)
The unary plus operator preserves the sign of a number, but when placed before a numeric string, it acts as a shorthand numeric type coercion operator, casting strings into integers or doubles without requiring explicit [int] or [double] syntax:
$numericString = "42"
$converted = +$numericString
$converted.GetType().Name
$converted + 8Int32
50Logical NOT Operator (!)
The exclamation mark (!) is the unary logical NOT operator. It inverts the boolean truth value of an expression. It functions as an exact shorthand alias for the -not operator.
- If an expression evaluates to
$true, prefixing it with!produces$false. - If an expression evaluates to
$false,$null,0, or an empty collection, prefixing it with!produces$true.
$isReady = $true
!$isReadyFalse$fileExists = Test-Path "C:\Missing.txt"
if (!$fileExists) {
Write-Output "File does not exist."
}File does not exist.where:
!$fileExistsevaluates to$trueonly when$fileExistsis$false.!and-notare functionally identical.!$fileExistsand-not $fileExistsproduce the same result.
Complete Example
$isRunning = $false
$targetPath = "C:\NonExistentFile.txt"
Write-Output "Inverted boolean: $(!$isRunning)"
if (!(Test-Path -Path $targetPath)) {
Write-Output "File does not exist: $targetPath"
}where:
!$isRunningconverts$falseto$true.!(Test-Path ...)wraps the cmdlet in parentheses so the path test evaluates first, and!inverts the resulting boolean.
pwsh ./logical-not.ps1Inverted boolean: True
File does not exist: C:\NonExistentFile.txtPractical Example: Resilient Service Polling Loop
The following script polls a Windows service during a restart sequence. It uses ! to test when the service is not yet running and postfix increment (++) to track attempts:
param (
[string]$ServiceName = "Spooler",
[int]$MaxRetries = 5
)
$attemptCount = 0
$isServiceUp = $false
Write-Output "Waiting for service '$ServiceName' to enter 'Running' state..."
while (!$isServiceUp -and ($attemptCount -lt $MaxRetries)) {
$attemptCount++
Write-Output "Check #${attemptCount}: Inspecting service state..."
$service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($null -ne $service -and $service.Status -eq "Running") {
$isServiceUp = $true
}
else {
Start-Sleep -Seconds 2
}
}
[PSCustomObject]@{
ServiceSearched = $ServiceName
IsRunning = $isServiceUp
TotalChecks = $attemptCount
ExceededRetries = (!$isServiceUp -and ($attemptCount -ge $MaxRetries))
}where:
!$isServiceUpinverts the boolean flag to continue looping while the service is down.$attemptCount++increments the counter by 1 on each iteration.!$isServiceUp -and ...evaluates whether the poll failed after exhausting retries.
Execute the script from the console:
pwsh ./wait-for-service.ps1 -ServiceName "Spooler" -MaxRetries 3Waiting for service 'Spooler' to enter 'Running' state...
Check #1: Inspecting service state...
ServiceSearched IsRunning TotalChecks ExceededRetries
--------------- --------- ----------- ---------------
Spooler True 1 False