Private/Release-SpecPreviousComPort.ps1
function Release-SpecPreviousComPort { <# .SYNOPSIS Releases a previous COM port from the COM Name Arbiter database. .DESCRIPTION This function releases a previous COM port entry from the COM Name Arbiter database. It calculates the appropriate byte and bit positions, updates the binary array, and modifies the registry accordingly. .PARAMETER OldPort The previous COM port value to be released. .OUTPUTS System.Int32 Returns 400 if the COM port is successfully released. Returns 401 if an error occurs during the release process. .EXAMPLE $statusCode = Release-SpecPreviousComPort -OldPort 3 if ($statusCode -eq 400) { Write-Host "COM port released successfully." } elseif ($statusCode -eq 401) { Write-Host "Failed to release COM port." } .NOTES Author : owen.heaume Version : 1.0 #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [int]$OldPort ) Begin { $Byte = ($OldPort - ($OldPort % 8)) / 8 $Bit = 8 - ($OldPort % 8) if ($Bit -eq 8) { $Bit = 0 $Byte = $Byte - 1 } } Process { try { $ComDB = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\COM Name Arbiter" -Name ComDB -ErrorAction Stop -ErrorVariable x $ComBinaryArray = ([convert]::ToString($ComDB.ComDB[$Byte], 2)).ToCharArray() while ($ComBinaryArray.Length -ne 8) { $ComBinaryArray = , "0" + $ComBinaryArray } $ComBinaryArray[$Bit] = "0" $ComBinary = [string]::Join("", $ComBinaryArray) $ComDB.ComDB[$Byte] = [convert]::ToInt32($ComBinary, 2) Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\COM Name Arbiter" -Name ComDB -Value ([byte[]]$ComDB.ComDB) -ErrorAction Stop -ErrorVariable x Write-Host "COM port released successfully.`n" -ForegroundColor DarkGreen return 400 } catch { Write-Host "Unable to release previous port from COM database: $x" -ForegroundColor DarkYellow return 401 } } } |