Comparing csv files in Powershell using Compare-Object

痞子三分冷 提交于 2019-11-26 17:22:01

问题


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


来源:https://stackoverflow.com/questions/19040159/comparing-csv-files-in-powershell-using-compare-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!