简体   繁体   中英

Import and parse specific data from CSV-file by using PowerShell

Hello all and best wishes for 2022!

I have the following CSV file:

Name,EmployeeID,File
JohnDoechebox,0009001,ImageBig1.png
JohnDoechebox,0009001,ImageBig2.png
JohnDoechebox,0009001,ImageFlat1.jpg
JohnDoechebox,0009001,ImageFlat2.jpg
JaneJefferson,0009006,IntDoc.docx
JaneJefferson,0009006,IntDoc2.docx
JaneJefferson,0009006,IntImage.jpg
JaneJefferson,0009006,ExtImage.jpg

I want to import the CSV file, this I can do with Import-CSV . Then I want to foreach the imported CSV file so that all rows get parsed.

I have been testing a bit and I came up with the following:

$Name = @()
$EmployeeID = @()

# Importing the CSV file and fill the array

Import-Csv -Path "C:\Temp\TestNew.csv" |`
    ForEach-Object {
        $Name += $_."Name"
        $EmployeeID += $_."EmployeeID"

    Write-Host "Your name is $($_.Name) and your Employee ID is $($_.EmployeeID)"

    }

This works as expected. So now I want to build it so that I can get all the files for that specific user based on the EmployeeID (because names can be duplicate, EmployeeID is always unique) and output the files by Write-Host . Like this:

Write-Host "Your name is $($_.Name) and your Employee ID is $($_.EmployeeID)" You have the following files:

Later I also want to execute an action with each file to copy it somewhere.

Any help would be greatly apreciated! Thanks in advance!

This can be done as follow

$list = import-csv 'C:\Temp\TestNew.csv' | Group-Object EmployeeID
foreach ($user in $list){

Write-Host "Your name is $($user.group.name[0]) and your Employee ID is $($user.Name) , You have the following files:"

$user.Group.file

}

To get all files with a specific EmployeeID value, use the Group-Object cmdlet to group the entries from the CSV by that specific column:

Import-Csv -Path "C:\Temp\TestNew.csv" |Group-Object EmployeeID |ForEach-Object {
    # Get the whole list of file names
    $groupOfFileNames = $_.Group |ForEach-Object File
    # Pick the name from the first entry in the grouped list
    $userName = $_.Group[0].Name

    Write-Host "Your name is $($_.Name) and your Employee ID is $($_.EmployeeID)" 
    Write-Host "You have the following files: [$($groupOfFileNames -join ', ')]"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM