简体   繁体   English

使用 PowerShell 从 CSV 文件导入和解析特定数据

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

Hello all and best wishes for 2022!大家好,2022 年最好的祝愿!

I have the following CSV file:我有以下 CSV 文件:

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 .我想导入 CSV 文件,我可以使用Import-CSV来完成。 Then I want to foreach the imported CSV file so that all rows get parsed.然后我想foreach导入的 CSV 文件,以便解析所有行。

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 .所以现在我想构建它,以便我可以根据 EmployeeID 获取该特定用户的所有文件(因为名称可以重复,EmployeeID 始终是唯一的)和 output 文件由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:要获取具有特定EmployeeID值的所有文件,请使用Group-Object cmdlet 按该特定列对 CSV 中的条目进行分组:

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 ', ')]"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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