steveo448
steveo448

Reputation: 57

How to retrieve multiple values from a string into an array in powershell

I'm looking to find a way to retrieve all of the MX records listed in a string into a text file.
So far I've got a script that gives me an HTML output from which I've used:

$Records = Get-Content -Path "C:\NETESP\MXRecords\MXRecordsHTML.txt" | Select-String -SimpleMatch -Pattern "MX: "

This results in $Records containing a string of:

<DIV class="well transcript">&nbsp;&nbsp;0&nbsp;&nbsp;nsb.nic.uk&nbsp;&nbsp;156.154.101.3&nbsp;&nbsp;NON-AUTH&nbsp;&nbsp;Recieved 2 Referrals , 
rcode=&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NS: ns.mainnameserver.com,NS: ns2.mainnameserver.com,&nbsp;&nbsp;<BR><BR>&nbsp;&nbsp;1&nbsp;&nbsp;ns2.
mainnameserver.com&nbsp;&nbsp;79.170.43.3&nbsp;&nbsp;AUTH&nbsp;&nbsp;Recieved 2 Answers , rcode=&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MX: exchange
=engine01-20052-1.icritical.com/pref=10,MX: exchange=engine02-20052-2.icritical.com/pref=20,&nbsp;&nbsp;<BR><BR></DIV></DIV></DIV></SPAN><TD>mx: </TD>

Is there a way to get the MX records and preferences values into a text file? Depending on which server this is run, there may be anywhere up to 6 MX records.

Upvotes: 0

Views: 1165

Answers (1)

Keith Hill
Keith Hill

Reputation: 201622

Modify your Select-String like so:

... | Select-String 'MX:\s*([^,]+)' -AllMatches | 
      Foreach {$_.Matches | Foreach {$_.Value}}

You need to create a capture group ([^,]+) in your regex. This will allow you to extract just that part of the matched text alter. You will also want to specify -AllMatches if there can be more than one MX record per line. After that you will want to enumerate each of the Matches and spit our their value (which will be the capture group text).

BTW this capture group assumes that each MX record ends with a comma. If that's not the case, you'll need to find the appropriate regex to capture just the MX record from the surrounding text.

Upvotes: 1

Related Questions