Public/Set-SpecNewDeviceToComPort.ps1
function Set-SpecNewDeviceToComPort { <# .SYNOPSIS Moves a device from one specified COM port number to another. .DESCRIPTION The Set-SpecNewDeviceToComPort function allows you to move a device from one specified COM port number to another in Windows. It iterates through the available COM ports, checks if the device is attached to the current COM port, and, if necessary, updates the COM port settings to move the device to the desired COM port. .PARAMETER CurrentPortNumber Specifies the current COM port number where the device is connected. .PARAMETER TargetPortNumber Specifies the target COM port number to which the device should be moved. .EXAMPLE Set-SpecNewDeviceToComPort -CurrentPortNumber 3 -TargetPortNumber 1 Moves the device from COM3 to COM1. .NOTES Author : owen.heaume Version : 1.0 #> [CmdletBinding()] param ( [parameter(Mandatory = $true)] [int]$CurrentPortNumber, [parameter(Mandatory = $true)] [int]$TargetPortNumber ) # Convert the port numbers to strings $CurrentPortString = "COM$CurrentPortNumber" $TargetPortString = "COM$TargetPortNumber" # Get the COM port details for all serial ports $comPorts = Get-WmiObject Win32_PnPEntity | Where-Object { $_.caption -match '\(COM\d+\)' } # Iterate through the COM ports foreach ($comPort in $comPorts) { $device = $comPort.PNPDeviceID # Check if a device is attached to the specified current COM port $oldPort = Get-SpecComPort -inputString $comport.name if ($oldPort -eq $CurrentPortString) { Write-Host "Device '$($comPort.Description)' found on '$CurrentPortString'. Moving to '$TargetPortString'..." -ForegroundColor DarkYellow # Check if the device is already on the target COM port if ($oldPort -eq $TargetPortString) { Write-Host "Device is already on '$TargetPortString'. No action needed." -ForegroundColor DarkGreen return } else { # Move the device to the target COM port $deviceKey = "HKLM:\SYSTEM\CurrentControlSet\Enum\$($comPort.PNPDeviceID)" $portKey = "$deviceKey\Device Parameters" try { Set-ItemProperty -Path $portKey -Name 'PortName' -Value $TargetPortString -ErrorAction Stop Set-ItemProperty -Path $deviceKey -Name 'FriendlyName' -Value "$($comPort.Description) ($TargetPortString)" -ErrorAction Stop Write-Host "Device '$($comPort.Description)' set to '$TargetPortString'" -ForegroundColor DarkGreen } catch { Write-Error "Failed to update the COM port settings: $_" } } # No need to continue checking other COM ports break } } #Write-Host "Device not found on '$CurrentPortString'." -ForegroundColor Red } |