Kellen Stuart
Kellen Stuart

Reputation: 8895

Powershell - Export-Csv prints "System.Text.RegularExpressions.Match[]" instead of the match

I wrote a function that searches for all IP's in a given directory:

function searchips
{
    param(
        [Parameter(Mandatory=$false)][string]$dir = $(pwd)
    )

    ls -Recurse -Force `
    | Select-String -Pattern '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' -AllMatches `
    | ? { 
        $matches = ($_.Matches | Select-Object -Unique)
        return $matches.Count -gt 1 -or $matches[0].Value -ne '127.0.0.1' 
    } `
    | select Path,Matches,FileName,LineNumber,Line
}

When I try to pipe the output to a CSV everything is fine except for the Matches column:

My Call: searchips | Export-Csv outfile.csv

And it spits out outfile.csv below...

enter image description here

As you can see, I'm getting System.Text.RegularExpressions.Match[] in the Matches column of my CSV.

In ISE the output without piping to Export-Csv looks like this:

enter image description here

Every other programming language taught me that brackets mean array, so I tried replacing Matches with Matches[0] and no dice.

Apparently those brackets are not an array but perhaps a property or something? Any ideas?

Upvotes: 0

Views: 454

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Matches is a collection, but you can't use Matches[0] in Select-Object because it's not the name of a property. Use a calculated property to get values from a property that holds a collection.

If you just want the first match you can use something like this:

select Path, @{n='Matches';e={$_.Matches[0].Value}}, FileName, LineNumber, Line

If you want all matches as a string use something like this:

select Path, @{n='Matches';e={$_.Matches.Groups.Value -join '|'}}, FileName,
       LineNumber, Line

If you want each match as a separate record you need something like this:

ForEach-Object {
  foreach ($ip in $_.Matches.Groups.Value) {
    New-Object -Type PSObject -Property @{
      Path       = $_.Path
      Match      = $ip
      FileName   = $_.FileName
      LineNumber = $_.LineNumber
      Line       = $_.Line
    }
  }

Upvotes: 2

Related Questions