Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic List Insert method

While I have no problem when adding arrays to a generic list, I am facing issues when trying to insert them :

$myList = [System.Collections.Generic.List[string]]::new()
[string[]]$myArr1 = "one", "two", "three"
[string[]]$myArr2 = "four", "five", "six"
$myList.AddRange($myArr2)
$myList.Insert(0, $myArr1)
$myList

is returning

one two three
four
five
six

while

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

one
two
three
four
five
six

is awaited.
I have tried $myList.Insert(0, {$myArr1}.Invoke()) without any success.

Facing another issue :

$mypart = [System.Collections.Generic.List[CimInstance]]::new()
[CimInstance[]]$disk0 = Get-Partition -DiskNumber 0
[CimInstance[]]$disk1 = Get-Partition -DiskNumber 1
$mypart.AddRange($disk1)
$mypart.Insert(0, $disk0)
$mypart

Here, Insert method throw an error "overload with 2 arguments not found".

Thanks for helping 🙂

>Solution :

Just like .AddRange() (rather than just .Add()) is required to append the elements of a collection (individually) in a single operation, you need to use .InsertRange() (rather than just .Insert()) to do the same for an insert operation.

The reason that the attempting .Insert() with a [string] array did not fail is that PowerShell quietly converted the string array to a single string, by space-concatenating the elements (as "$('one', 'two')" would). For a [CimInstance] array, no such conversion can be performed, which is why an error occurs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading