Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Named group regular expressions in Powershell

Posted on 2013-01-15
2
Medium Priority
?
998 Views
Last Modified: 2013-01-31
In powershell I am trying to search a file specified by the $mypath variable for a given regular expression pattern $mypattern. The regular expression uses named groups of the form '(?<age>[0-9]*Years)'. How can I get the named group value into a variable that I can use. I have tried the following as a guess but havent got anywhere.

$result = select-string -path $mypath -pattern $mypattern | foreach-object {$_.matches} | foreach-object {$_.groups['age']} | select-object value

Open in new window

0
Comment
Question by:Blowfelt82
2 Comments
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 38778761
try:

select-string -path $mypath -pattern $mypattern | select -expand Matches | foreach {$_.groups["age"].value}

Open in new window

0
 
LVL 71

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 38778832
Select-String seems to ignore named captures. The groups are always named like the captured value, which makes it less useful. You will have to use the numeric index into the Groups collection to get access:
select-string -path $mypath -pattern $mypattern |
  select -Expand Matches |
  foreach-object {$_.Groups[1].Value}

Open in new window

0

Featured Post

Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Loops Section Overview

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question