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 8, Working with .NET):
$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($oldArray, # Source 50, # Copy from index of Source $newArray, # Destination 49, # Copy to index of Destination 50) # Number of elements to copy
Using a for loop:
$newArray = for ($i = 0; $i -lt $oldArray.Count; $i++) { if ($i -ne 49) { $oldArray[$i] } }