Read or Import CSV File in PowerShell

We can read text from CSV file using powershell’s Import-Csv cmdlet. The Import-Csv cmdlet provides a way to read in data from a comma-separated values file (CSV) and then display that data in tabular format within the Windows PowerShell console. Consider the following CSV file (AllUsers.CSV).

Name,Department,Title
Kevin,Research,Manager
Smith,"IT Security",Administrator
Kim,"IT Security",Administrator
Mike,Finance,Accountant

Use the following command to import csv file and display output in tabular format in powershell console:

Import-Csv C:ScriptsAllUsers.csv

If you want to work with csv file inputs, you can read values as row by row by piping the imported data into ForEach function.

Import-Csv C:ScriptsAllUsers.csv |
    ForEach-Object {
        $Name = $_.Name
        $Title = $_."Title"

       Write-Host "Name: " $Name "; Title:" $Title
    }

We can filter CSV input values, pipe the imported data to the Where-Object cmdlet to filter csv input.

Import-Csv C:ScriptsAllUsers.csv |  Where-Object {$_.Title -eq "Administrator"} |
    ForEach-Object {
        $Name = $_.Name
        $Title = $_."Title"

       Write-Host "Name: " $Name "; Title:" $Title
    }
Advertisement

Leave a Comment