This tip details the steps needed to batch remove Plug-and-Play devices from a Windows system in PowerShell. The script is designed to remove devices that have multiple copies installed, but can be adapted to fit other criteria. It requires the PowerShell ISE and pnputil.exe to work.
Introduction
Recently while troubleshooting Windows devices, I found several hundred copies of some multimedia devices installed on a few of my systems. I wanted to get rid of all these duplicates but the GUI only allows a single device to be uninstalled at a time. Doing this manually would have been a very time-consuming process. After scouring the internet for a way to remove them all at once and only repeatedly seeing "It can't be done" (or other unhelpful advice), I came up with this solution in Powershell that works nicely.
I thought I'd post it here to help anyone else trying to remove a lot of devices, but was unable to find a solution for it. This works in Windows 10 and presumably 7 and 8, although I haven't tried it on those platforms.
Using the Code
The script can be executed in a single command, but for clarity, I broke it up into a few script lines. It doesn't have to be run as a .PS1 script, but it does only seem to work in the PowerShell ISE.
To uninstall all devices with a given name, use the following script:
$deviceName="Name of the device(s) you want to remove"
foreach ($dev in (Get-PnpDevice | Where-Object{$_.Name -eq $deviceName})) {
&"pnputil" /remove-device $dev.InstanceId
}
Or as a single command:
foreach ($dev in (Get-PnpDevice | Where-Object{$_.Name -eq "Name of device to remove"))
{ &"pnputil" /remove-device $dev.InstanceId }
And that's it!
Points of Interest
There are other ways to enumerate and filter the devices (such as Get-WmiObject
), but this was the only way I found that also works with hidden devices.
History
- 16th September, 2021: Initial version