listpowershell

how to get a string of a mutable array?


This is something that keeps throwing me, I figured out a work around a few weeks back but I forgot:

$l=[System.Collections.Generic.List[string[]]]::new()
$l.Add("one", "two", "three")
$l.ToString()                                                  #returns ---> System.String[]
"$l"                                                           #returns ---> System.String[]           
 [string]$l                                                  #returns ---> System.String[]       
 $l -join "`n"                                              #returns ---> System.String[]       

I am expecting something like the following or something else as dictated by the $ofs variable:

one
two
three

Am on pwsh 7.4


Solution

  • Leaving aside that the $l.Add("one", "two", "three") call cannot work, I assume that your intent is to create a list whose elements are strings ([string]) rather than arrays of strings ([string[]]).

    Therefore, change:
    $l=[System.Collections.Generic.List[string[]]]::new()
    to:
    $l=[System.Collections.Generic.List[string]::new()

    To put it all together:

    # Create a list whose elements are strings.
    $l = [System.Collections.Generic.List[string]]::new()
    # Add 3 elements; note the use of .AddRange() rather than .Add()
    $l.AddRange([string[]] ("one", "two", "three"))
    
    $l.ToString() # -> 'System.Collections.Generic.List`1[System.String]'
    
    "$l"           # -> 'one two three'
    [string] $l    # ditto
    $l -join "`n"  # -> "one`ntwo`nthree"
    

    Note that "$l" and [string] $l do respect the value of the $OFS preference variable, if defined; in the latter's absence, a single space is used.