在PowerShell中,如何使用分隔符连接和合并字符串数组?

huangapple go评论61阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月16日 11:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定