Home > front end >  Compare two CSV Files and output existing equalities
Compare two CSV Files and output existing equalities

Time:10-19

Im basically comparing an short list of PC names with our active directory, the first file is the list of pcs i have to check, the second file is the ad list that i got with following command

$ADcomputer = get-adcomputer -Filter "name -Like '*'" -Searchbase "DC=**,DC=******,DC=**"

($ADcomputer).name | Out-file "C:\temp\ADComputer.csv"

In both lists there are only pc names in split "A" most of them are built like "PC23425" just with various numbers (there are some exceptions of course but i dont need to check for them only for pcs with this pattern).

The list.csv is built like this

PC020682
PC020891
PC020953
PC021999

I read several posts about this and im very sure i need to use a foreach loop for that, but since i dont use powershell very often i aint sure how to pull it off.

What i try is

$Path = "C:\temp"
$ComputerList = Import-Csv -Path "$($path)\ADcomputer.csv"
$ComputerAchiv = Import-Csv -Path "$($path)\List.csv"
   

But i have no idea how to build the foreach loop.

CodePudding user response:

Although a CSV file format is not fully standardized, as mentioned by @Theo PowerShell expects the first row to be the header record by default. The header row will be used to define the property names of the object(s) eventually emitted by the Import-Csv cmdlet. In the case your CSV file doesn't contain a header row, you might manually add the header row (column names, property names) by using the -Header parameter, e.g.: -Header username.
For PowerShell you files are simple lists (without properties), which you might read using the Get-Content cmdlet:

$ComputerList = Get-Content -Path "$($path)\ADcomputer.csv"
$ComputerAchiv = Get-Content -Path "$($path)\List.csv"

To find out the items that the lists share, you might use the Where-Object cmdlet:
(see also: Comparing two arrays & get the values which are not common)

$ComputerList |Where-Object { $ADcomputer.name -eq $_ }

Next Level

Although this might be a direct answer to your question. It might not bring you much as you probably do want to deal with PowerShell standard CSV files (Meaning PowerShell object lists) and join those. For this, see e.g.: In Powershell, what's the best way to join two tables into one?

  • Related