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.
Below is the
sample csv file “Sourcedata.csv” we’ll be using as example
TaskID, AssignTo, Duration
001, Tom, 55
002, Rand, 230
003, Mat, 86
##Script Starts
here
##First declare a variable to store
full path of csv file
$SourceFile =
“C:\Sourcedata.csv”;
##Use Test-Path
to ensure that given file exists
if(Test-Path
$SourceFile)
{
## Case 1 – Read
the full CSV file and store result in a variable
$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
$selectedRecords
= Import-csv -path $SourceFile|Where-Object {$_.AssignTo.Contains(“Rand”)}
##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 while importing csv
$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
foreach($record
in $allRecords)
{
$assignTo =
$record.AssignTo;
Write-Host
$assignTo
## Do your
operation here..
}
}
##Script Ends
here
No comments:
Post a Comment