使用 Powershell 从字符串中获取键值

rAJ*_*rAJ 5 regex powershell

我正在尝试在 powershell 中使用 Regex 获取键值。

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name
Run Code Online (Sandbox Code Playgroud)

我想要这样的输出:

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

Name : :value1,key2:value2,
Run Code Online (Sandbox Code Playgroud)

小智 7

如果您使用逗号分隔键:值对,这应该完成您所追求的。

$string = "key1:value1,key2:value2,key3:value3"
$ht = @{} # declare empty hashtable
$string -split ',' | % { $s = $_ -split ':'; $ht += @{$s[0] =  $s[1]}} 
# split the string by ',', then split each new string on ':' and map them to the hashtable
Run Code Online (Sandbox Code Playgroud)

输出以下内容(注意默认情况下它们没有排序)

PS C:\> $ht

Name                           Value
----                           -----
key3                           value3
key1                           value1
key2                           value2
Run Code Online (Sandbox Code Playgroud)

  • 你可以用`$string -replace ':','=' -split ',' | 来达到同样的效果。ConvertFrom-StringData` (2认同)