Very new to Powershell and trying to get my head around how to compare two Excel files, both with the column 'User_ID' in common, and output only the records sharing the User_ID value to a new Excel file.
File 1 'Powershell_Results.xlsx' contains a single column 'User_ID' with 80 rows of data. File 2 'Master_Data.xlsx' contains three columns: 'Host_name', 'Serial_number' and 'User_ID' with 4150 rows of data.
Powershell_results.csv = User_ID AVHQSX BKSAXS CFNSAU
Master_Data.csv = User_ID AVHQSX BKSAXS CFNSAU
Serial_Number 566409 127629 466160
Hostname WDC00001 WDC00006 WDC00007
Unsure if a first step of conversion from XLSX to CSV would make things easier.
I feel like I'm close but can't work out the remaining few kinks. Working on a Mac FWIW:
# load both csv files
$pwsh_results = Import-Csv -Path 'Desktop\Code\Powershell_results.csv'
$master_data = Import-Csv -Path 'Desktop\Code\Master_Data.csv'
# loop through records
$result = foreach ($User_ID in $master_data){
# find a record in the pwsh_results.csv where the .User_ID is equal to the .User_ID in the master_data.csv
$pwsh_results | Where-Object { $_.User_ID -eq $_.User_ID } | ForEach-Object {
# create an object with properties from both csv files combined
$obj = $emp | Select-Object @{Name = 'User_ID'; Expression = {$_.User_ID}}, * -ExcludeProperty id
# add the details from $pwsh_results to this
$obj | Add-Member -MemberType NoteProperty -Name 'User_ID' -Value $_.User_ID
$obj | Add-Member -MemberType NoteProperty -Name 'Serial_Number' -Value $_.Serial_Number
$obj | Add-Member -MemberType NoteProperty -Name 'Hostname' -Value $_.Hostname
# output the combined object to be collected in variable $result
$obj
}
}
# show the results in the console
$result | Format-Table -AutoSize
# save as new csv file
$result | Export-Csv -Path 'Desktop\Code\Matches.csv' -NoTypeInformation