使用键值对

时间:2015-10-21 09:10:00

标签: powershell

我从文本文件中读取了这个字符串。如何获得每个键的值?

statusId=0  statusError=Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for connections to the remote server.

由于内容的原因,我无法在空格或分号上进行简单的拆分。

2 个答案:

答案 0 :(得分:1)

如果字符串总是格式

statusId=<numbers> statusError=<whatever>

可以使用-match运算符使用正则表达式进行拆分。如果字符串格式发生变化,这种方法需要调整正则表达式,所以要小心。

您没有指定key的含义,因此我猜statusIdstatusError是关键。

像这样,

$s = "statusId=0  statusError=Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for connections to the remote server." # Hard-coded data for demo
$s -match "^(statusId=\d+\s+)(.+)"
# Output
True

$Matches
# Output
Name           Value
----           -----
2              statusError=Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for connections to ...
1              statusId=0
0              statusId=0  statusError=Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for con...
$Matches[1]
# Output
statusId=0
$Matches[2]
# Output
statusError=Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for connections to the remote server.
($Matches[2] -split '=')[1]
# Output
Info: Using ID '8d07afe6-4fc3-47a3-9583-571f79ca15ae' for connections to the remote server.

模式"^(statusId=\d+\s+)(.+)"查找以statusId=开头的字符串,至少有一个数字后面跟着至少一个空格,然后就可以了。访问结果是通过automatic $Matches变量完成的。然后使用-split '='将匹配分为两部分,并使用[1]索引器,&#34;信息:&#34;部分已到达。

答案 1 :(得分:0)

最简单的方法是拆分键:

$statusId,$statusError = $string -split 'statusId=|statusError='