Import or Read Line by Line from a CSV File using PowerShell

In PowerShell, we can use the Import-Csv cmdlet to read content from a CSV file and create table-like custom objects. Each column in the CSV file becomes a property of the custom object and the items in rows become the property values.

Use the below command to export a sample CSV content.

Get-Process | Select-Object Id, ProcessName, WorkingSet | 
  Export-CSV "C:\Temp\SampleData.csv" -NoTypeInformation -Encoding UTF8

This example describes how to import or read row by row in a loop from a CSV file. The Import-Csv command read the file and sends the result to the ForEach-Object cmdlet to loop the rows one by one.

#Import and read the rows one by one
Import-CSV "C:\Temp\SampleData.csv" | ForEach-Object { 

#Current row object
$CSVRecord = $_

#Read column values in the current row 
$Id = $CSVRecord.'Id'
$ProcessName = $CSVRecord.'ProcessName'

#Display values
Write-Host "$Id - $ProcessName"

}

Import CSV file and Create Custom Object for Each CSV Row

This example describes how to read content from a CSV file and loop the items row by row. Inside the loop, we can create a custom object for each row. The columns in the CSV are converted as the object’s property names and the row items are property values. Finally, the script exports the custom objects into another CSV file.

$Result = @() #Custom object result array

#Import and read the CSV rows one by one
Import-CSV "C:\Temp\SampleData.csv" | ForEach-Object { 

#Current row object
$CSVRecord = $_

#Creat a custom object and add it to the result array
$Result += New-Object PSObject -property $([ordered]@{ 
Id = $CSVRecord.'Id'
ProcessName = $CSVRecord.'ProcessName'
WorkingSet = $CSVRecord.'WorkingSet'
})

}

#Export the custom object array to another CSV file
$Result | Export-CSV "C:\Temp\SampleData2.csv" -NoTypeInformation -Encoding UTF8

#Display the result array
$Result | FT
Advertisement

Leave a Comment