Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, April 8, 2013

How to extract information from one CSV file using information in another

This question came from a user who needed to use a list of users names in one csv file to select what information will be extracted from another csv file.  To set this up, I created two csv files.  The first one, UserData.csv, contains a list of users and some data associated with each one.

 

UserName,Prop1,Prop2
Jason,abc,123
Matt,456,789
Debbie,def,123
Beth,456,thr
Tom,der,324

The second file, UserName.csv, contains only the users whose information I want to extract from the UserData.cvs file.

UserName
Jason
Debbie

Here is the code.

 

$Path = "C:\PowerShell"

 

$UserList = Import-Csv -Path "$($path)\UserName.csv"

$UserData = Import-Csv -Path "$($path)\UserData.csv"

 

foreach ($User in $UserList)

{

    ForEach ($Data in $UserData)

    {

        If($User.Username -eq $Data.UserName)

        {

            # Process the data

            $Data

        }

    }

 

}

Now, if you want to keep the data flowing through the PowerShell Pipeline, try this code instead.

$Path = "C:\PowerShell"

 

$UserList = Import-Csv -Path "$($path)\UserName.csv"

$UserData = Import-Csv -Path "$($path)\UserData.csv"

 

$UserList | ForEach-Object { $User = $_

    $UserData | ForEach-Object {

        If ($User.Username -eq $_.UserName)

        {

            Write-Output $_

        }

    }

} | FT -AutoSize # Keep it in the pipeline.

No comments: