PowerShell Remove item [0] from an array

arraylist, arrays, powershell

Solution

An alternative option is to use Powershell's ability to assign multiple variables (see this other answer).

$arr = 1..5
$first, $rest= $arr

$rest
2
3
4
5

It's been a feature of Powershell for over a decade. I found this functionality from an MSDN blog post:

Problem

I'm struggling a bit to remove the first line (item ID) of an array. ``` $test.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array ``` To list all the options I tried `,$test | gm` and it clearly states: ``` Remove Method void IList.Remove(System.Object value) RemoveAt Method void IList.RemoveAt(int index) ``` So when I try `$test.RemoveAt(0)` I get the error: ``` Exception calling "RemoveAt" with "1" argument(s): "Collection was of a fixed size."At line:1 char:1 + $test.RemoveAt(1) + ~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NotSupportedException ``` So I finally found here that my array needs to be of the type `System.Object` to be able to use `$test.RemoveAt(0)`. Is it best practice to declare all the arrays in the beginning of the script as a list? Or is it better to convert the arrays with `$collection = ({$test}.Invoke())` to a list later on when this functionality is needed? What are the pro's and cons of both types? Thank you for your help.

Original source

Related problems