将逗号分隔的字符串转换为列表

时间:2018-09-21 18:05:39

标签: powershell

我有以下Powershell代码:

$Credentials = 'Credentials: myacct1,myacct2'

$runtimes = $Credentials -match "Credentials: (?<content>.*)"
$runtimeList = $matches['content']
Foreach ($runtime in $runtimeList)
{
    Write-Host $runtime
}

这只是返回myacct1,myacct2,我希望它在列表中进行迭代

myacct1
myacct2

2 个答案:

答案 0 :(得分:3)

我敢肯定,您只需要使用,String.Split()分割匹配的字符串即可。

$Credentials = 'Credentials: myacct1,myacct2'

$runtimes = $Credentials -match "Credentials: (?<content>.*)"
$runtimeList = $matches['content'].Split(",")
Foreach ($runtime in $runtimeList)
{
    Write-Host $runtime
}

# Output:
# myacct1
# myacct2

答案 1 :(得分:2)

要提供更多PowerShell惯用的解决方案:

PS> 'Credentials: myacct1,myacct2' -replace '^Credentials: ' -split ','
myacct1
myacct2
  • -replace '^Credentials: '从字符串中去除前缀​​Credentials: (用(隐含的)空字符串替换)。
  • -split ','通过,
  • 将剩余的字符串拆分为令牌数组