Reading a CSV File Quickly Using PowerShell

Excel File
Excel File

Often time we need to import data from CSV files into PowerShell to perform additional tasks.  In this post, I would like 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 its quick.  I hope you find this helpful.

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

LoginName
DisplayName
UserPrincipalName

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.
     ...
}
About Vikram 7 Articles
I am just an IT person trying to share as much knowledge as possible hoping someone will find it helpful. It just takes time to organize everything from my head into something that makes sense.