10

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

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

1 Answer 1

20

Your -join statement 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 ","

# 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 ','

# Outputs: 1,2,3

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

slist | Join-String -Separator ','

See also about_Parsing for more context on the differences between Argument mode and Expression mode.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the Join-String suggestion. It can use prefix and suffixes easily: Join-String -Separator ',' -OutputPrefix '[' -OutputSuffix ']'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.