开发者

Powershell using a regex to create a new hash table object

开发者 https://www.devze.com 2023-01-06 18:44 出处:网络
I\'m trying to parse a file that contains blocks of text in this format(there can be 1-n of these): -----------------------------------------------------------

I'm trying to parse a file that contains blocks of text in this format(there can be 1-n of these):

-----------------------------------------------------------
KB Article Number(s): 2028769, 2072493, 2120979, 2143880, 2163958, 2163980, 980653, 980883, 981155, 981867, 982321, 982850
Language: All (Global)
Platform: x64
Location: (http://foo.bar.com)
Password: foo
-----------------------------------------------------------

The text is coming from an MS Hotfix request email if anyone is interested.

I have the following powershell one liner:

 $file | select-string "(?<Name>\w+):(?<Value>.*)" -allmatches | SELECT @{N="Name";E={$_.Matches[0].Groups[1].Value}}, @{N="Value";E={$_.Matches[0].Groups[2].Value}}

This give me a flat set of 开发者_运维知识库name value pairs, I would like it to return an array of hashtables with each of the 5 Keys populated.

I'm not sure if the problem is my regex or how I'm accessing the matches (There must be a less verbose way of picking these out).


It's not pretty but I think it will work for you:

$ht = @{}
$file | %{if ($_ -match '(?<Name>[^:]+):(?<Value>.*)') {
          $ht.($matches.Name) = $matches.Value.Trim()} `
          elseif ($ht.Count) {$ht;$ht.Clear()}}

Using the -match operator is a tad easier because you can use the $matches variable directly without having to go through Select-String's MatchInfo.Matches property. BTW I'm assuming here $file was populated by a call to Get-Content i.e. each line is a string in a string array.

0

精彩评论

暂无评论...
验证码 换一张
取 消