Remove a row from a powershell array/collection/hashtable

arrays, powershell

Solution

Arrays are immutable in PowerShell, you can't add or remove elements from them. What you can do is:

a) Make a new array and filter out the one you don't want (e.g. with `-ne`):

$data = $data | ? {$_.Server -ne "Total"}

or

b) Select everything up to the last element by index (might be resource hungry on a big array, I don't know):

$data = $data[0..($data.Count-2)]

or

c) Cast it to `[System.Collections.ArrayList]`, which is mutable, then remove an element from it:

$data = [System.Collections.ArrayList]$data
$data.RemoveAt($data.Count-1)

Problem

I have a large array (imported from an Excel spreadsheet) that has a "total" row that I want to delete. It is always the last item in the array. I've tried to find a way to just delete the last array item, but can't. Data and code sample below: ``` $data = Import-XLSX -Path "C:\Pathtofile\spreadsheet.xlsx" -Sheet "SheetName" -RowStart 3 $data | ? {$_.Server -eq "Total"} Server : Total VLAN : IP Address : CPU : 84 RAM : 313 C:\ : 2840 D:\ : 17950 OS Version : OS Edition : SQL Version : SQL Edition : Datastore : Reboot : Notes : ``` I'd like to be able to delete this row from the array. I've tried the following: ``` $data.Remove("Total") Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size." At line:1 char:1 + $ImportCSV.Remove("Total") + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NotSupportedException ``` If I check the array type, I get the following: ``` $data.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array ``` If I retype the object like so, I get the following: ``` $data = {$data}.Invoke() $data.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Collection`1 System.Object $data.Remove("Total") False ``` This does not delete the item. What am I missing here?

Original source