Comparing csv files in Powershell using Compare-Ob

2019-01-27 10:17发布

问题:

I am new to powershell and I having a little dilemma with a script I created to compare two csv files. The first csv has only one column called "Database Name" in it. The secound csv has a many columns and I only care about two of them "Database Name" and "Host Name". Right now the script compares only the "Database Name" column which works great!! and exports to Differences.csv. However, I would also like to see the corresponding "Hostname" column for each "Database Name" in the difference file.

$northdb = Import-Csv -Path ".\northdb.csv" -Header "Database Name" | Sort-object Property "Database Name" -Unique 

$sdb = Import-Csv ".\Current\SQLDatabaseInventory.csv" -Header "hostname",h2,h3,h4,h5,"Database Name"  |Sort-Object -Property "Database Name" -Unique

Compare-Object $northdb $sdb -Property  "Database Name" |  Where-Object{$_.SideIndicator -eq '=>'} | 
Select-Object  "Database Name" | export-csv .\Difference.csv -NoTypeInfo

Please assist

回答1:

If you add the -PassThru to your compare object you'll receive all the object properties

Compare-Object $northdb $sdb -Property  "Database Name" -PassThru

Then you can also export hostname :

Compare-Object $northdb $sdb -Property  "Database Name" -PassThru |  Where-Object{$_.SideIndicator -eq '=>'} | Select-Object  "Database Name", "hostname" | export-csv .\Difference.csv -NoTypeInfo