# Is there a better way to compare 2 files and remove duplicates

**URL:** <https://forums.powershell.org/t/is-there-a-better-way-to-compare-2-files-and-remove-duplicates/15541>\
**Category:** PowerShell Help\
**Created:** [January 28, 2021, 7:47am UTC](https://forums.powershell.org/t/is-there-a-better-way-to-compare-2-files-and-remove-duplicates/15541 "2021-01-28T07:47:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![w7-65a](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/w7-65a/32/1302_2.png) [@w7-65a](https://forums.powershell.org/u/w7-65a)\
**Post date:** [January 28, 2021, 7:47am UTC](https://forums.powershell.org/t/is-there-a-better-way-to-compare-2-files-and-remove-duplicates/15541/1 "2021-01-28T07:47:35Z")

</div>

I want to find a better way to remove computers from a list so commands are not run against them again once they have their results collected in a csv file. Is there a nicer way or better way to do this?

`# Compare the Computers.txt and the Results.csv and make a new Computers.txt`  
`# file for only the computers that are not in the Results.csv file.`

`if (-not (Test-Path -Path “C:\Results.csv”) ) { New-Item -ItemType ‘File’ -Path “C:\Results.csv” }`  
`$Csv = Import-Csv -Path “C:\Results.csv”`  
`$Array = @()`  
`foreach ($Item in (Get-Content -Path “C:\Computers.txt”)) {`  
`if ($Csv.ComputerName -contains $Item) {`  
`#“$Item info has already been collected”`  
`}`  
`else {`  
`$Array += $Item`  
`}`  
`}`  
`if (Test-Path -Path “C:\Computers.txt”) { Remove-Item -Path “C:\Computers.txt” -Force }`  
`$Array | Select-Object -Unique | Sort-Object | Out-File -FilePath “C:\Computers.txt”`

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [January 28, 2021, 8:40am UTC](https://forums.powershell.org/t/is-there-a-better-way-to-compare-2-files-and-remove-duplicates/15541/2 "2021-01-28T08:40:13Z")

</div>

Please take a look at the cmdlet [Compare-Object](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/compare-object?view=powershell-7.1). You should read the complete help including the examples to learn how to use it.

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:27pm UTC](https://forums.powershell.org/t/is-there-a-better-way-to-compare-2-files-and-remove-duplicates/15541/3 "2024-05-16T20:27:58Z")

</div>


