PowerShell Reading From CSV File

Reading from a CSV, and doing some operation on the records returned by CSV is one of the most common tasks in PowerShell. I’ll try to explain different cases here with sample code.

The following is the sample csv file “Sourcedata.csv” we’ll be using:

TaskID, AssignTo, Duration

001, Tom, 55
002, Rand, 230
003, Mat, 86
  1. ##Script Starts here##First declare a variable to store full path of csv file  
  2. $SourceFile = “C: \Sourcedata.csv”;##Use Test - Path to ensure that given file exists  
  3. if (Test - Path $SourceFile) {##Case 1–Read the full CSV file and store result in a variable  
  4.     $allRecords = Import - csv - path $SourceFile##Case 2–If csv has huge data and you want selected rows only, you can filter data with where condition  
  5.     $selectedRecords = Import - csv - path $SourceFile | Where - Object   
  6.     {  
  7.         $_.AssignTo.Contains(“Rand”)  
  8.     }##Case 3 - If csv has data but no column headers and you want to put headers in order to manipulate data later, you can add headers  
  9.     while importing csv  
  10.     $allRecordswithHeader = Import - csv - Header TaskID, AssignTo, Duration - path $SourceFile#Now you have data with you and want to start operations on each of the row, simple - iterate through records  
  11.     foreach($record in $allRecords)   
  12.     {  
  13.         $assignTo = $record.AssignTo;  
  14.         Write - Host $assignTo##Do your operation here..  
  15.     }  
  16. }  
  17. ##Script Ends here  
Happy scripting.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now