Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

Batch Uninstall Devices in PowerShell

5.00/5 (1 vote)
16 Sep 2021CPOL1 min read 23.5K  
How to uninstall multiple devices at once using PowerShell ISE
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:

PowerShell
$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:

PowerShell
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)