Reading a CSV File Quickly Using PowerShell

Excel File

Often time we need to import data from CSV files into PowerShell to perform additional tasks.  In this post, I would like to share one of the ways I use PowerShell to read values from CSV files.  I am not saying this is the only best way but I like this way because of its quick.  I hope you find this helpful.

So, let’s say you want to read a CSV file called users.csv that has the following columns as shown above.

LoginName
DisplayName
UserPrincipalNameCode language: Excel (excel)

Create a new .ps1 file with the following and execute it from the PowerShell window.

# Specify the source file name
$SourceFile = c:\users.csv

# Define your Array variables
$strName = @()
$strDispName = @()
$strUPN = @()

# Read file data to arrays
Import-Csv $SourceFile |
     ForEach-Object {
          $strName += $_.LoginName
          $strDispName += $_.DisplayName
          $strUPN += $_.UserPrincipalName
}

# Count the number of values
$cntValues = $strName.Length

# This is just to define the variable used in the For loop below
$i = 0

# Enumerate through the arrays to use each value
for ($i=0; $i -lt $cntValues; $i++)
{
     # Retrieve each row from the array
     $strMyName = $strName[$i].ToString()
     $strMyDispName = $strDispName[$i].ToString()
     $strMyUPN = $strUPN[$i].ToString()

     # Then do whatever you like with the value from each row.
     # ...
}
Code language: PowerShell (powershell)