Assign, add and assign, and subtract and assign

The assignment operator (=) is used to assign values to variables and properties, for example, let's look at assigning a value to a variable:

$variable = 'some value' 

Or, we might change the PowerShell window title by assigning a new value to its property:

$host.UI.RawUI.WindowTitle = 'PowerShell window' 

The add and assign operator (+=) operates in a similar manner to the addition operator. The following example assigns the value 1 to a variable, then += is used to add 20 to that value:

$i = 1 
$i += 20 

The preceding example is equivalent to writing the following:

$i = 1 
$i = $i + 20 

The += operator may be used to concatenate strings:

$string = 'one' 
$string += 'one' 

As we saw with the addition operator, attempting to add a numeric value to an existing string is acceptable. Attempting to add a string to a variable containing a numeric value is not:

PS> $variable = 1
PS> $variable += 'one'
Cannot convert value "one" to type "System.Int32". Error: "Input string was not in a correct format."
At line:2 char:1
+ $variable += 'one'
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger

It is possible to work around this by assigning a type to the variable:

[String]$string = 1 
$string += 'one' 

The += operator may be used to add single elements to an existing array:

$array = 1, 2 
$array += 3 

You can also use it to add another array:

$array = 1, 2 
$array += 3, 4 

The += operator may be used to join together two hashtables:

$hashtable = @{key1 = 1} 
$hashtable += @{key2 = 2} 

As we saw using the addition operator, the operation will fail if one of the keys already exists.

The subtract and assign operator (-=) is intended for numeric operations, as shown in the following examples:

$i = 20 
$i -= 2 

After this operation has completed, $i will be assigned a value of 18.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.228.35