如何在powershell中用分隔符连接字符串数组?

hfsqlsce  于 2023-03-08  发布在  Shell
关注(0)|答案(1)|浏览(154)

PS C:\用户\用户\ps-模块〉更多信息。\我的字符串.测试. 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:\用户\用户\ps模块〉pwsh.\我的字符串.测试. 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

为什么当数组来自函数return时与直接声明时的处理方式不同?

a8jjtwal

a8jjtwal1#

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

相关问题