how to count rows in a csv and then loop through the contents

笑着哭i 提交于 2019-12-13 09:31:14

问题


I have a csv that i want to check the count of rows and then loop through the contents. Im using the code at the bottom to get the count which works but im not sure how i can loop through the csv and get the values in each column. Ive read that i can do it using the select-object cmdlet if i specify the column names however this code will work on a number of csv's all with different column names. Any ideas how i can make this work?

$csv = Import-Csv -Path $requestFile  | measure

if(($csv).count-1 -gt 1){
    //do something
}

回答1:


You don't need to pipe to Measure to get the row count. In fact, the variable you've stored in $csv is not the csv data but the output from Measure, so you should remove the pipe to Measure.

Here's an example:

PS C:\temp> $csv = Import-Csv .\test.csv
PS C:\temp> # Here you can perform your check on the size of the csv
PS C:\temp> $csv.Count
4
PS C:\temp> # ... and you can get all the data like this:
PS C:\temp> $csv


Year        : 1997
Make        : Ford
Model       : E350
Description : ac, abs, moon
Price       : 3000.00

Year        : 1999
Make        : Chevy
Model       : Venture "Extended Edition"
Description :
Price       : 4900.00

Year        : 1999
Make        : Chevy
Model       : Venture "Extended Edition, Very Large"
Description :
Price       : 5000.00

Year        : 1996
Make        : Jeep
Model       : Grand Cherokee
Description : MUST SELL!
              air, moon roof, loaded
Price       : 4799.00

My csv looks like this:

Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00



回答2:


Import-Csv creates a list of objects. This list already has a Count property, so you don't need to measure it yourself:

$csv = Import-Csv -Path $requestFile

if ($csv.Count -gt 2) {
    # do something
}

Not sure why you'd want to restrict the "do someting" to CSVs with more than 2 rows, though.

If you also want to loop over the columns of each row you can do that with a nested loop as described in this answer:

$csv = Import-Csv -Path $requestFile

if ($csv.Count -gt 2) {
    $csv | ForEach-Object {
        foreach ($property in $_.PSObject.Properties) {
            doSomething $property.Name, $property.Value
        } 
    }
}

For further help you'd need to explain what you actually want to do with the columns.



来源:https://stackoverflow.com/questions/32870931/how-to-count-rows-in-a-csv-and-then-loop-through-the-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!