PowerShell: Assignment Operators

By Xah Lee. Date: . Last updated: .

Assign

varName = right-hand-side

assign

x=3

Add then assign

varName += right-hand-side

add then assign.

  • if right-hand-side is number, add number.
  • if right-hand-side is string, append to end.
  • if right-hand-side is array, append to end.
  • if right-hand-side is hashtable, merge hashtable. (value must be a hashtable)
$x = 3
$x += 2
Write-Output $x
# 5
$x = "cat"
$x += " and dog"
Write-Output $x
# cat and dog
$x = @(3,4,5)
$x += 6
Write-Output $x
# 3
# 4
# 5
# 6
$x = @{a = 1; b = 2}
$x += @{c = 4}
Write-Host $x
# [a, 1] [b, 2] [c, 4]

others

varName -= right-hand-side

substract then assign

varName *= right-hand-side

times then assign

varName /= right-hand-side

divide then assign

varName %= right-hand-side

take remainder then assign

varName ??= right-hand-side

if right-hand-side is not null, assign to left-hand-side

$x = 0
$x += 2
Write-Host $x
# 2

increment

varName++

return the original variable value first, then increment by 1, then assign.

$x = 0
$result = $x++
Write-Host $x
# 1
Write-Host $result
# 0
++varName

increment by 1, then assign, then return the variable value.

$x = 0
$result = ++$x
Write-Host $x
# 1
Write-Host $result
# 1

decrement

varName--

decrement by 1

--varName

decrement by 1

PowerShell, variable and assignment

PowerShell operators