Skip to content

PowerShell Unary Operators

How PowerShell unary operators (++, --, +, -, !) modify single values, invert booleans, and handle numeric sign changes with precedence rules.

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

Consolepowershell
$count = 5
$count++
Write-Output $count
Outputplaintext
6
Consolepowershell
$count = 5
$count--
Write-Output $count
Outputplaintext
4

Both operators can also be used as a prefix, applying the change before the value is used in an expression:

Consolepowershell
$count = 5
Write-Output (++$count)
Write-Output $count
Outputplaintext
6
6

Prefix vs. Postfix Evaluation

increment-decrement.ps1powershell
$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 $counterA to 6.
  • ++$counterB increments $counterB to 6 immediately, then assigns 6 to $resultB.
Consolepowershell
pwsh ./increment-decrement.ps1
Outputplaintext
Type                 Returned FinalValue
----                 -------- ----------
Postfix ($counter++)        5          6
Prefix (++$counter)         6          6

Unary 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:

Consolepowershell
$temperature = 15
-$temperature

$offset = -50
-$offset
Outputplaintext
-15
50
Consolepowershell
$value = 10
$negative = -$value
Write-Output $negative
Outputplaintext
-10
Consolepowershell
$negative = -10
$positive = -$negative
Write-Output $positive
Outputplaintext
10

where:

  • 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:

Consolepowershell
$numericString = "42"
$converted = +$numericString

$converted.GetType().Name
$converted + 8
Outputplaintext
Int32
50

Logical 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.
Consolepowershell
$isReady = $true
!$isReady
Outputplaintext
False
Consolepowershell
$fileExists = Test-Path "C:\Missing.txt"
if (!$fileExists) {
    Write-Output "File does not exist."
}
Outputplaintext
File does not exist.

where:

  • !$fileExists evaluates to $true only when $fileExists is $false.
  • ! and -not are functionally identical. !$fileExists and -not $fileExists produce the same result.

Complete Example

logical-not.ps1powershell
$isRunning = $false
$targetPath = "C:\NonExistentFile.txt"

Write-Output "Inverted boolean: $(!$isRunning)"

if (!(Test-Path -Path $targetPath)) {
    Write-Output "File does not exist: $targetPath"
}

where:

  • !$isRunning converts $false to $true.
  • !(Test-Path ...) wraps the cmdlet in parentheses so the path test evaluates first, and ! inverts the resulting boolean.
Consolepowershell
pwsh ./logical-not.ps1
Outputplaintext
Inverted boolean: True
File does not exist: C:\NonExistentFile.txt

Practical 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:

wait-for-service.ps1powershell
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:

  • !$isServiceUp inverts 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:

Consolepowershell
pwsh ./wait-for-service.ps1 -ServiceName "Spooler" -MaxRetries 3
Outputplaintext
Waiting for service 'Spooler' to enter 'Running' state...
Check #1: Inspecting service state...

ServiceSearched IsRunning TotalChecks ExceededRetries
--------------- --------- ----------- ---------------
Spooler              True           1           False
Navigation