How to determine if my virtual machines have a USB controller attached and how to remove it?

In the wake of recent published VMSA-2022-0004 admins can wonder how to determine if Virtual Machine has a USB controller attached.

Now thanks to PowerCLI it is an easy task.

NOTE: I did not come up with this code, this code was originally published on VMware advisory website

$VMs = Get-VM

$USBHardware = "VirtualUSBController|VirtualUSBXHCIController"
foreach ($VM in $VMs) {
    $VMview = Get-VM $VM | Get-View

    $VMview.Config.Hardware.Device | Where-Object {$_.GetType().Name -match $USBHardware} | Foreach-Object {
        $devname = $_.GetType().Name
        Write-Host "$VM`: VM has a $devname device." -ForegroundColor Yellow
    }
}

Before admins can remove USB controllers, The virtual machine may need to be powered off, depending on the guest operating system and its support for hot-add/hot-remove devices.

$VMs = Get-VM $vmname

$USBHardware = "VirtualUSBController|VirtualUSBXHCIController"

foreach ($VM in $VMs) {
    $VMview = Get-VM $VM | Get-View
    $VMview.Config.Hardware.Device | Where-Object {$_.GetType().Name -match $USBHardware} | Foreach-Object {
        $devname = $_.GetType().Name
        Write-Host "$VM`: Removing the $devname device." -ForegroundColor Yellow
        $Config = New-Object VMware.Vim.VirtualMachineConfigSpec
        $Config.DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec
        $Config.DeviceChange[0] = New-Object VMware.Vim.VirtualDeviceConfigSpec
        $Config.DeviceChange[0].Operation = "remove"
        $Config.DeviceChange[0].Device = $_
        # $VM.ExtensionData.ReconfigVM($Config)
    }
}

Replace or assign a value to the $vmname variable, and uncomment the ReconfigVM line to actually make the change (it is commented here for safety). It is also set up for use with the longer hardware list from above (though you may need to run it twice to remove the AHCI controllers, because of dependencies). Also, by removing $vmname altogether you can iterate over all virtual machines in an environment (dangerous!).

As always, please read the disclaimer before applying any of the code/scripts to your environment. Also please read the disclaimer on the VMware website.

NOTE: Before applying a workaround, please remove snapshots. Snapshots capture VM configuration, which means that if you applied a workaround and revert from a snapshot, you may be vulnerable again. Hence patching is recommended method of remediation.

Please like and share to spread the knowledge in the community.

If you want to chat with me please use Twitter: @AngrySysOps

Visit my FB page: https://www.facebook.com/AngrySysOps

Read my blog: https://angrysysops.com

Subscribe to my channel : https://www.youtube.com/channel/UCRTcKGl0neismSRpDMK_M4A

Please leave the comment