Share via


Find string using pattern and return only the matched string

Question

Thursday, October 8, 2009 11:04 PM

Hi all

Scratching my head with this one and could use some help.

I have a file that contains an sddl dump.  I am trying to find each SID in the file and write the value to a variable.  The following regular expression seems to provide the pattern match.

"s-(.)*\"

When I run the following commend it returns the whole file contents

select-string -path $file -pattern "s-(.)*\"

I just want to return the strings matching the pattern and not the entire file contents.  I understand that the output from select-string is a MatchInfo object, but I can't see any properties or methods that would help me extract just the string matching the pattern.

Any thoughts?

Tony

All replies (4)

Friday, October 9, 2009 12:31 AM ✅Answered

I've always reached into [Regex]::Matches when I've had to do this.  Not as easy as one would like...

Get-Content -Path data.txt | %{ [Regex]::Matches($_, "S-[0-9\-]*") } | %{ $_.Value }

Friday, October 9, 2009 1:15 AM ✅Answered

If you're using PowerShell v2, you can also check out example 9:
http://technet.microsoft.com/en-us/library/dd315403.aspx


Friday, October 9, 2009 7:00 AM

Hi Tony,

If you’re using Powershell V1, please refer to the following thread:

Return only matches from Select-String
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/d5bbd2fb-c8fa-43ed-b432-79ebfeee82ea

Thanks.
This posting is provided "AS IS" with no warranties, and confers no rights.


Monday, October 12, 2009 8:22 PM

Thanks all :-)

The following works for me:

$sids = [regex]::matches($filecontents, "S(-\d+){2,8}")

Tony