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
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
Share Improve this question edited yesterday mklement0 438k68 gold badges701 silver badges911 bronze badges asked 2 days ago Ralf_ReddingsRalf_Reddings 1,5313 silver badges16 bronze badges 1 |2 Answers
Reset to default 3Leaving 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.
The following code, gets the result, but I'm in 7.5:
$l=[System.Collections.Generic.List[string[]]]::new()
$l.Add("one")
$l.Add("two")
$l.Add("three")
$l
.add()
has a mistake that I often fall for, I over looked while writting this quesiont. I meant$l.Add(("one", "two", "three"))
. mklement0 linked to the$ofs
section of the docs, below. – Ralf_Reddings Commented yesterday