how do I concatenate and join an array of strings with a delimiter in powershell?
Asked Answered
D

1

6

PS C:\Users\User\ps-modules> more .\MyStrings.Tests.ps1

function slist { "1", "2", "3" }

Describe 'StringTests' {

  It 'literal -join' {
    "1", "2", "3" -join "," | Should -Be "1,2,3"
  }

  It 'literal -join' {
    @("1", "2", "3") -join "," | Should -Be "1,2,3"
  }

  It 'slist returns a list of string' {
    slist | Should -Be @("1", "2", "3")
  }

  It 'slist -join' {
    slist -join "," | Should -Be "1,2,3"
  }

}

PS C:\Users\User\ps-modules> pwsh .\MyStrings.Tests.ps1

Starting discovery in 1 files.
Discovery found 4 tests in 169ms.
Running tests.
[-] StringTests.slist -join 55ms (53ms|2ms)
 Expected '1,2,3', but got @('1', '2', '3').
 at slist -join "," | Should -Be "1,2,3", C:\Users\User\ps-modules\MyStrings.Tests.ps1:17
 at <ScriptBlock>, C:\Users\User\ps-modules\MyStrings.Tests.ps1:17
Tests completed in 731ms
Tests Passed: 3, Failed: 1, Skipped: 0 NotRun: 0

Why is the array treated differently when it comes from a function return vs when it's literally declared?

Dumuzi answered 16/2, 2023 at 3:58 Comment(0)
F
13

-join ',' is interpreted as arguments being passed to your slist function, with this slight modification we can see it better:

function slist { "1", "2", "3" + $args }
slist -join ","

Which outputs:

1
2
3
-join
,

In this case you would need to use the grouping operator ( ), as stated in the doc:

(...) allows you to let output from a command participate in an expression.

(slist) -join "," -eq '1,2,3' # True

As an alternative in PowerShell 6.2+ you can use Join-String:

slist | Join-String -Separator ','
Flagrant answered 16/2, 2023 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.