简体   繁体   中英

How to copy contents from one CSV into another CSV with powershell?

i have 2 csv files: each got 3 columns, i want to compare the first column and if it matches it will copy the content in the other columns for example:

1 csv:

column1   column2    column3
aaa       bla        baba
ccc       bla        babab3
abc       bla        bababa3

2 csv:

column1   column4     column5
abc       dla2        blabla2
ddd       dla         blabla
ccc       dla1        blabla1
aaa       dla1        blabla1

updated csv:

column1   column2   column3   column4   column5 
aaa       bla        baba     dla1      blabla1
ccc       bla        babab3   dla1      blabla1
abc       bla        bababa3  dla2      blabla2

thanks,

# Import both CSV files.
$rowsA = Import-Csv 1.csv
$rowsB = Import-Csv 2.csv

# The name of the shared column to join by.
$sharedCol = 'Column1'

# Get the column names of 2.csv, excluding the shared one.
$colsB = $rowsB[0].psobject.Properties.Name -ne $sharedCol

# Create a map (hashtable) that maps the shared column
# values to the column values of the matching 2.csv rows.
$map = @{}
$rowsB.ForEach({ $map[$_.$sharedCol] = $_.psobject.Properties[$colsB] })

# Construct empty helper properties for those $sharedCol values in 1.csv
# that have no counterpart in 2.csv
$emptyPropsB = 
  ([pscustomobject] @{} | Select-Object -Property $colsB).psobject.Properties

$rowsA | ForEach-Object {
  $rowA = $_
  # Find the matching 2.csv row's column values. If not found, use empty ones.
  $colValuesB = $map[$rowA.$sharedCol]
  if (-not $colValuesB) { $colValuesB = $emptyPropsB }
  # Append the column values from the 2.csv row to the 1.csv row at hand.
  $colValuesB.ForEach({ $rowA.psobject.Properties.Add($_) })
  $rowA # Output the merged row.
} # | Export-Csv -NoTypeInformation -Encoding utf8 updated.csv

Outputs to the display ; remove the # from the last line to export to a CSV file instead.

Note: If you want to skip 1.csv rows that have no matching 2.csv row, replace
if (-not $colValuesB) { $colValuesB = $emptyPropsB } with
if (-not $colValuesB) { return }
Also, you then don't need the $emptyPropsB =... statement.

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