PowerShell Assignment Operators


Assignment operators is performing a numeric operation on the existing value before assignment. Assume that we have variable $a = 15.

+=   $a += 15 same as $a = $a + 15 
-=    $a -= 15  same as  $a = $a - 15 
*=   $a *= 15  same as $a = $a * 15 
/=    $a /= 15  same as $a = $a / 15 
%=  $a %= 15 same as $a = $a % 15 

Example for +=.

$a = 5
$a += 6 # a = 11
$a = 'Windows'
$a += ' PowerShell' # a = Windows PowerShell

$arr = 1, 2, 3
$arr += 2
$arr # 1 2 3 2

$a = @{a = 1;b = 2;}
$a += @{c = 3} # a = 1, b = 2, c = 3

Example for -=.

$a = 5
$a -= 2 # 3
$a = 1, 2, 3
$a[1] -= 1 # 1 1 3
$a -= 1 # this will generate error

You cannot use the -= operator to delete the values of a variable. To delete all the values that are assigned to a variable, assign a value of $null or "" to the variable (see powerShell arrays). Let's take look more examples for *=.

$a = 3
$a *= 4 # 12
$a = "powerShell"
$a *= 3 # powerShellpowerShellpowerShell
$a = 1, 2, 3
$a[1] *= 5 # 1 10 3

Last for /= and %=.

$a = 8
$a /= 2
$a = 1, 4, 5
$a[1] /= 2 # 1 2 5
$a = 7
$a %= 2 # 1

Subscribe to receive free email updates:

0 Response to "PowerShell Assignment Operators"

Post a Comment