DevOps | Scripts | Automation

Powershell

How to work with CSV file in PowerShell – Part II?

In the first part, we have created a CSV file with various methods. Today we will discuss how we can use the existing CSV file as an input to utilize its values inside PowerShell.

Suppose, we have a CSV file called ADUserData.csv as shown below. We will work with that file.

To retrieve the data of the CSV,

Import-Csv C:\Temp\ADUserData.csv

We can perform the pipeline commands on CSV as well.

Import-Csv C:\Temp\ADUserData.csv | ft -AutoSize

Grouping Objects.

Import-Csv C:\Temp\ADUserData.csv | Group-Object -Property Location | Select Name, Count

Filtering CSV file,

Import-Csv C:\Temp\ADUserData.csv | where{$_.Dept -eq "HR"} | ft -AutoSize

To process each object, we can use foreach command.

$csvfile =Import-Csv C:\Temp\ADUserData.csv

foreach($obj in $csvfile){
    $displayname = $obj.FirstName + " $($obj.LastName)"
    New-ADUser -Name $obj.FirstName -DisplayName $displayname -SamAccountName $obj.UserName -Department $obj.Dept  
}

With the foreach loop, we can iterate through each line and use the values. Here we have used csv values to create a New AD user.

Loading