2

I have a csv file call Full-List.csv that have columns like this

Old_URL    Number

I have another csv file Sub-List.csv that have columns like this

Old_URL  New_URL Title  Owner 

I'm just wondering how can I compare the two csv file using Old_URL column and output to another csv file that look something like this. Basically it'll include a "Number" column now.

New_URL  Title  Owner  Number
$left = Import-Csv 'C:\Users\Downloads\New folder\Full-List.csv'
$right = Import-Csv 'C:\Users\Downloads\New folder\Sub-List.csv'

Compare-Object -ReferenceObject $left -DifferenceObject $right -Property Old_URL -IncludeEqual -ExcludeDifferent | 
    ForEach-Object {
        $iItem = $_
        $ileft = $left.Where({$_.Old_URL -eq $iItem.Old_URL })
        $iright = $right.Where({$_.Old_URL -eq $iItem.Old_URL})
        [pscustomobject]@{
             New_URL = $iright.New_URL
             Number =$ileft.Number
             Title = $iright.Title
             Owner =$iright.Owner
        }
    } | Export-Csv 'C:\Users\Downloads\New folder\Combined.csv' -NoTypeInformation

There are matching Old_URL in both file but some reason my Combined.csv output is empty so any help or suggestion would be really appreciated.

aasenomad
  • 405
  • 2
  • 11
  • Using this [`Join-Object script`](https://www.powershellgallery.com/packages/Join)/[`Join-Object Module`](https://www.powershellgallery.com/packages/JoinModule) (see also: [In Powershell, what's the best way to join two tables into one?](https://stackoverflow.com/a/45483110/1701026)): `Import-Csv .\Full-List.Csv |Join (Import-Csv .\Sub-List.Csv) -on Old_URL |Export-Csv .\Combined.Csv` – iRon Apr 20 '23 at 18:11

1 Answers1

2

You should really consider using hash table for this, Group-Object -AsHashtable does a great job simplifying this process. Once you have your lookup table you can enumerate the Full-List CSV and output only those objects having a correlated Old_URL value:

$map = Import-Csv path\to\Sub-List.csv | Group-Object Old_URL -AsHashTable -AsString

Import-Csv path\to\Full-List.csv | ForEach-Object {
    if($map.ContainsKey($_.Old_URL)) {
        [pscustomobject]@{
            New_URL = $map[$_.Old_URL].New_URL
            Title   = $map[$_.Old_URL].Title
            Owner   = $map[$_.Old_URL].Owner
            Number  = $_.Number
        }
    }
} | Export-Csv path\to\mergedCsv.csv -NoTypeInformation
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37