How can I quickly find VMs with serial ports in PowerCLI

1.7k Views Asked by At

I have a script that takes about 15 minutes to run, checking various aspects of ~700 VMs. This isn't a problem, but I now want to find devices that have serial ports attached. This is a function I added to check for this:

Function UsbSerialCheck ($vm)
{
    $ProbDevices = @()
    $devices = $vm.ExtensionData.Config.Hardware.Device
    foreach($device in $devices)
    {
        $devType = $device.GetType().Name
        if($devType -eq "VirtualSerialPort")
        {
            $ProbDevices += $device.DeviceInfo.Label
        }
    }
    $global:USBSerialLookup = [string]::join("/",$ProbDevices)
}

Adding this function adds an hour to the length of time the script runs, which is not acceptable. Is it possible to do this in a more efficient way? All ways I've discovered are variants of this.

Also, I am aware that using global variables in the way shown above is not ideal. I would prefer not to do this; however, I am adding onto an existing script, and using their style/formatting.

1

There are 1 best solutions below

0
On

Appending to arrays ($arr += $newItem) in a loop doesn't perform well, because it copies all existing elements to a new array. This should provide better performance:

$ProbDevices = $vm.ExtensionData.Config.Hardware.Device `
  | ? { $_.GetType().Name -eq 'VirtualSerialPort' } `
  | % { $_.DeviceInfo.Label }