1

I have a powershell script to find particular instances and then export them to CSV. Here's an example of the way the code works

$items = "Hello Tim", "Hola Bob", "Hello Susan" 
$filter = $items | Select-String -Pattern "Hello"
$filter | Select-Object Line, Matches | Export-Csv "C:\log.csv"
Invoke-Item "C:\log.csv"

When I run the Select-Object in PS, it's nicely formatted info like this:

powershell

However, when I export to CSV, it exports the whole object and writes it as the following string: System.Text.RegularExpressions.Match[]

csv export

How can I get it to export just the first match or a listing of all matches into a single field when writing to CSV?

2 Answers 2

3

Here is one way using a PSObject:

$items = "Hello Tim", "Hola Bob", "Hello Susan" 
$filter = $items | Select-String -Pattern "Hello"
$filter | % {New-Object PSObject -property @{
  Line = $_.Line
  Matches = $_.Matches.Groups[0].Value}
} | Export-Csv "C:\log.csv" -NoTypeInformation
Sign up to request clarification or add additional context in comments.

Comments

1

Quickly note that Matches is an array which may create issues exporting to a csv.
Try joining the array into a string with a chosen delimiter. I used "::" in my example.

$filter | Select Line, @{Expression={$_.Matches -join "::"}; Label="Matches"} | Export-Csv "C:\log.csv"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.