Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 300 CSV files all separated in a directory.

I want to get one specific criteria from each CSV and put it into another using PowerShell.

This is the line I have, but doesn't seem to work.

Get-ChildItem -Filter "*Results.csv" | Get-Content | Where-Object {$_.NAME -eq "Cage,Johnny"} | Add-Content "test.csv"

I filtered for the specific CSVs I wanted in my directory with gci, Got the content of each using Get-Content and Where the value is Johnny Cage in the NAME column, and Add-Content into a test.csv file but doesn't work. Any help would be great!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to deserialize your CSV text into objects with properties that can be referenced. Then you can compare the Name property. You can do the following if all your csv files have the same headers.

Get-ChildItem -Filter "*Results.csv" | Import-Csv |
    Where-Object {$_.NAME -eq "Cage,Johnny"} |
        Export-Csv "test.csv"

If your CSV files contain different headers, then you have a couple of options. One, you could create your output CSV with all possible headers that exist across all files (or just the headers you want as long as they are the same across all files). Second, you could just output your data rows and have a broken CSV.

# Broken CSV Approach
Get-ChildItem -Filter "*Results.csv" | Import-Csv |
    Where-Object {$_.NAME -eq "Cage,Johnny"} | Foreach-Object {
        $_ | ConvertTo-Csv -Notype | Select-Object -Skip 1
    } | Add-Content test.csv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...