Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

cmd - PowerShell CSV, take a specific row from each line and combine it into one CSV

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...