I'm trying to find unique values/merge two CSVs. But it doesn't seem to be working.
For some reason the code doesn't return unique values (doesn't merge). The output is always the values of the first CSV. In this case it's returning the values of $Users1
. If i change it to $UserUnique = $Users2 + $user1
it returns the values of $User2
Here's my code:
$Users1 = Import-Csv -Path \\share\user\Desktop\disabledusers.csv
$Users2 = Import-Csv -Path \\share\user\Desktop\disabledusers2.csv
$UserUnique = $Users1 + $user2
$UserUnique | Select-Object -Property * -Unique
Any ideas?
Thanks in advance.
My Ref link - How to merge two csv files in powershell with same headers and discard duplicate rows
More information as requested: Please find the CSVs and expected outcome attached below.
$Users1
name lastlogondate passwordlastset SAMAccountName Name1 20/03/2017 12:54 05/09/2013 13:43 Sam1 Name2 18/08/2016 10:31 04/03/2015 09:42 Sam2 Name3 11/09/2016 17:48 17/03/2015 12:02 Sam3 Name4 06/09/2016 08:46 06/10/2015 09:44 Sam4 Name5 07/09/2016 08:46 07/10/2015 09:44 Sam5 Name6 08/09/2016 08:46 08/10/2015 09:44 Sam6
$Uers2
name lastlogondate passwordlastset SAMAccountName Name1 20/03/2017 12:54 05/09/2013 13:43 Sam1 Name2 18/08/2016 10:31 04/03/2015 09:42 Sam2 Name3 11/09/2016 17:48 17/03/2015 12:02 Sam3 Name4 06/09/2016 08:46 06/10/2015 09:44 Sam4 Name7 09/09/2016 08:46 09/10/2015 09:44 Sam7 Name8 10/09/2016 08:46 10/10/2015 09:44 Sam8 Name9 11/09/2016 08:46 11/10/2015 09:44 Sam9 Name10 12/09/2016 08:46 12/10/2015 09:44 Sam10
Expected Outcome
name lastlogondate passwordlastset SAMAccountName Name1 20/03/2017 12:54 05/09/2013 13:43 Sam1 Name2 18/08/2016 10:31 04/03/2015 09:42 Sam2 Name3 11/09/2016 17:48 17/03/2015 12:02 Sam3 Name4 06/09/2016 08:46 06/10/2015 09:44 Sam4 Name5 07/09/2016 08:46 07/10/2015 09:44 Sam5 Name6 08/09/2016 08:46 08/10/2015 09:44 Sam6 Name7 09/09/2016 08:46 09/10/2015 09:44 Sam7 Name8 10/09/2016 08:46 10/10/2015 09:44 Sam8 Name9 11/09/2016 08:46 11/10/2015 09:44 Sam9 Name10 12/09/2016 08:46 12/10/2015 09:44 Sam10
Your issue is a simple typo: $user2
should be $users2
.
An undefined variable - $user2
, in this case - defaults to $null
, making the intended array concatenation operation $Users1 + $user2
a no-op: effectively, you get just $Users1
, and that explains your symptom (your attempt to swap the operands, $Users2 + $user1
, preserved the typo).
To prevent such typos, use Set-StrictMode -Version 1
or higher to make PowerShell report an error if an undefined variable is accessed (except inside "..."
).
Beyond that, however, I suggest bypassing Import-Csv
and the costly Select-Object -Property *
approach (see my answer to the linked question for an explanation), which both simplifies your code and makes it more efficient:
Get-Content \\share\user\Desktop\disabledusers.csv, \\share\user\Desktop\disabledusers2.csv |
Select-Object -Unique