使用Powershell将2个CSV文件中的数据合并为1个新CSV

时间:2016-10-10 18:46:23

标签: powershell csv

***为澄清而编辑:

我的ADP CSV包含与列出的完全相同的标题:操作日期,工作信息生效日期,位置名称,法定名称,员工状态代码,名字,姓氏,员工ID,职位,位置状态,位置城市,员工班级,雇用日期,工作终止日期,FLSA超时指标,FLSA状态。

我的Office 365 CSV包含与列出的完全相同的标题:DISPLAY NAME,EMAIL ADDRESS

我需要一张CSV列出:显示名称,电子邮件地址,城市,州,位置名称,职位。

我需要一个将两个文件组合在一起的Powershell脚本,只留下Office 365用户及其个人资料缺失的数据,例如城市,州,位置名称,职位。

我理解为Office 365列表创建哈希表,但每次创建一个它都会返回"数组索引被评估为Null"在我的理解中意味着我没有在哈希表中使用正确的头名称。

****再次编辑!我附上了我的代码。除了它创建的电子邮件列是空白之外,它会执行我需要的所有操作。我不再遇到表错误。

    $ItemsToKeep = 'First Name','Last Name','Employee Status Code','Location Name','Job Title','Location State'
    $ItemsToKeep += @{Name = "Display Name"; Expression = {$_.'First Name' + ' ' + $_.'Last Name'}}
    $ItemsToKeep += @{Name = "Email"; Expression = { $EmailLookupTable[$_.'Display Name'] }}

    $EmailLookupTable = @{}
    Import-Csv C:\O365LIST.csv |ForEach-Object {
    $EmailLookupTable[$_.'Display Name'] = $_.'Email Address'
    }



    Import-Csv C:\ADPLIST.csv |Where-Object {$_.'Employee Status Code' -eq 'Active'} | Select $ItemsToKeep | export-csv C:\Testing.csv -notypeinformation

1 个答案:

答案 0 :(得分:1)

首先,将第二个CSV加载到哈希表中,这样您就可以轻松地将显示名称从第一个CSV映射到电子邮件地址:

#Import the second CSV and use a hashtable to store the email address based on the display name
$EmailLookupTable = @{}
Import-Csv C:\employee_emails.csv |ForEach-Object {
    $EmailLookupTable[$_.'Display Name'] = $_.'Email Address'
}

使用现有脚本,而不是在每个操作之间导出到新文件,而是将它们全部链接在一个管道中 - 大部分代码可以通过一点点元编程自动完成!

# Automate away the task of replacing spaces with underscores
$ColumnsToKeep = "Location Name","Employee Status Code","Job Title","Location State","Location City","First Name","Last Name"
$PropertiesToSelect = $ColumnsToKeep |ForEach-Object {
    @{Name = $_ -replace ' ','_'; Expression = [scriptblock]::Create('$_."{0}"' -f $_)}
}

# Add the display name property
$PropertiesToAdd = @(@{Name = "Display_Name"; Expression = {$_.First_Name + ' ' + $_.Last_Name}})

# Add the Email address from the lookup table
$PropertiesToAdd += @{Name = "Email"; Expression = { $EmailLookupTable[$_.First_Name + ' ' + $_.Last_Name] }}

# 1. Import CSV
# 2. Filter on status
# 3. Select the properties to keep/rename
# 4. Select the properties from the previous step + the new ones
# 5. Export CSV
Import-Csv C:\ADPLIST.csv |Where-Object {$_.'Employee Status Code' -eq 'Active'} |Select-Object $PropertiesToSelect |Select-Object *,$PropertiesToAdd |Export-Csv C:\final.csv
相关问题