February 2019
Intermediate to advanced
626 pages
15h 51m
English
Removing elements based on an index requires the creation of a new array and omission of the value in the element in that index. In each of the following cases, an array with 100 elements will be used as an example; the element at index 49 (with the value of 50) will be removed:
$oldArray = 1..100
This method uses indexes to access and add everything we want to keep:
$newArray = $oldArray[0..48] + $oldArray[50..99]
Using the .NET Array.Copy static method (see Chapter 7, Working with .NET), we have the following:
$newArray = New-Object Object[] ($oldArray.Count - 1)
# Before the index
[Array]::Copy( $oldArray, # Source
$newArray, # Destination
49 # Number of elements to copy )
# After the index
[Array]::Copy(Read now
Unlock full access