英文:
how do I concatenate and join an array of strings with a delimiter in powershell?
问题
为什么当数组来自函数返回时与它被直接声明时会有不同的处理方式?
英文:
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?
答案1
得分: 7
-join '','' 被解释为将参数传递给您的 `slist` 函数,稍作修改,我们可以更清楚地看到:
function slist { "1", "2", "3" + $args }
slist -join "','"
输出为:
1
2
3
-join
,
在这种情况下,您需要使用分组运算符 ( )
,如文档中所述:
(...)
允许您让来自 命令 的输出参与表达式。
(slist) -join "','" -eq '1,2,3' # True
作为在 PowerShell 6.2+ 中的备选方案,您可以使用 Join-String
:
slist | Join-String -Separator '',''
英文:
-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 ','
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论