3

I need to read with powershell a lot of files and getting all email address. I tried this solution

$myString -match '\w+@\w+\.\w+'

The problem is that the variable $matches contains only the first match. Am I missing something?

Naigel
  • 9,086
  • 16
  • 65
  • 106
  • You have another problem you haven't noticed yet - your regex will miss valid email addresses, and probably match invalid ones. It's not a simple regex that matches valid email addresses - and it's a topic that comes up here on SO [quite](https://www.google.com/search?q=regex+to+match+email+address+site:stackoverflow.com) [frequently](http://stackoverflow.com/search?q=regex+match+email+address) – alroc Mar 20 '13 at 12:40
  • @alroc Thanks for your observation. In fact I'm using a different regex to find email addresses. Here it's only an example, just to understand the problem – Naigel Mar 20 '13 at 12:51

2 Answers2

5

-match returns strings with the content, so it works better with a string-array where it can find a match per line. What you want is a "global" search I believe it's called. In PowerShell you can do that using Select-String with the -AllMatches parameter.

Try the following:

(Select-String -InputObject $myString -Pattern '\w+@\w+\.\w+' -AllMatches).Matches

Example:

$myString = @"
user@domain.no hhaksda user@domain.com
dsajklg user@domain.net
"@

PS > (Select-String -InputObject $myString -Pattern '\w+@\w+\.\w+' -AllMatches).Matches | ft * -AutoSize

Groups            Success Captures          Index Length Value
------            ------- --------          ----- ------ -----          
{user@domain.no}     True {user@domain.no}      0     14 user@domain.no 
{user@domain.com}    True {user@domain.com}    23     15 user@domain.com
{user@domain.net}    True {user@domain.net}    48     15 user@domain.net
Frode F.
  • 52,376
  • 9
  • 98
  • 114
2

The Select-String approach works well here. However, this regex pattern is simply not suitable and you should review the following similar question: Using Regex in Powershell to grab email

Community
  • 1
  • 1