Removing elements from an array

Removing elements from an array is difficult because arrays are immutable. To remove an element, a new array must be created.

It is possible to appear to remove an element by setting it to null, for example:

$myArray = 1, 2, 3, 4, 5 
$myArray[1] = $null 
$myArray 

However, observe that the count does not decrease when a value is set to null:

PS> $myArray.Count 
5

Loops (or pipelines) consuming the array will not skip the element with the null value (extra code is needed to guard against the null value):

$myArray | ForEach-Object { Write-Host $_ } 

The Where  object may be used to remove the null value, creating a new array:

$myArray | Where-Object { $_ } | ForEach-Object { Write-Host $_ } 

Depending on usage, a number of ways are available to address removal. Removal by index and removal by value are discussed next.

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

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