Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate shortcuts containing a specific string

We have a lot of users with duplicate files on their Desktop (Windows 10). I want to create a script which runs every X minutes or just once after logging on to the system.

Our users are currently seeing the following shortcuts (.lnk):

  • Dummy.lnk (correct shortcut, should remain unchanged)
  • Dummy - copy.lnk (duplicated shortcut, should be removed)
  • Dummy-OFFICE-QB4V70A.lnk (duplicated shortcut containing the name of the computer, should be removed)

So in short I want to keep the 'original' shortcuts but I want to remove all shortcuts containing '- copy.lnk' and/or '-computername.lnk'.

I also tried using the %computername% variable but I have no idea how to implement this in my code. Every computer has a different and unique name so I can not use pre-defined computernames.

Any tips on how I can achieve this? I have tried using the code below, but this removes all .lnk (shortcut) files and not just the duplicates.

#(Get-ChildItem Dummy.lnk | Select-String -Pattern "OFFICE" | Select-Object -ExpandProperty path -Unique) | ForEach-Object{Remove-Item -Force -LiteralPath $_}

I prefer using Powershell so that I can deploy the script using Group Policy.

like image 305
Codemeister Avatar asked Apr 19 '26 09:04

Codemeister


1 Answers

I would use the Where-Object cmdlet to filter all shortcuts you want to remove and pipe them to the Remove-Item cmdlet:

Get-ChildItem -Path 'c:\yourPath' -Filter '*.lnk' | 
    Where-Object { $_.Name -match '- Copy\.lnk$' -or $_.Name -like "*$($env:Computername)*"} |
    Remove-Item
like image 96
Martin Brandl Avatar answered Apr 21 '26 22:04

Martin Brandl