How to Obtain a List of Available COM Ports using PowerShell

Abstract: Retrieve available COM ports in PowerShell using WMI or registry queries for automated device detection and scripting.

Created: 2026-08-12 by
You can obtain a list of available COM ports in PowerShell by querying the Win32_SerialPort WMI class or reading the registry under HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM. These methods retrieve both active and phantom ports, providing the necessary serial device identifiers for scripting and system administration tasks on Windows systems.

Understanding Serial Port Enumeration

Serial communication remains critical for industrial automation, embedded development, and legacy hardware integration. While modern systems rely heavily on USB-to-serial adapters, the underlying operating system still manages these connections through the same COM port architecture as traditional RS-232 interfaces. Identifying these ports programmatically allows administrators to automate device detection, configure serial terminals, or troubleshoot connectivity issues without manually inspecting Device Manager.

The most robust approach involves using Windows Management Instrumentation (WMI) or the Common Information Model (CIM). These technologies provide a standardized interface to query hardware resources. By leveraging PowerShell’s built-in cmdlets, you can extract detailed information about each serial port, including its description, device ID, and current status. This data is essential for scripts that need to dynamically assign baud rates or handle multiple connected devices.

Method 1: Using Win32_SerialPort WMI Class

The Win32_SerialPort class is the standard WMI provider for serial communications. It returns a comprehensive list of all serial ports recognized by the operating system. This method is preferred because it provides metadata beyond just the port name, such as the manufacturer and hardware ID.

Get-WmiObject -Class Win32_SerialPort | Select-Object Name, Description, DeviceID, Status

When you run this command, PowerShell queries the WMI service and returns an array of objects. Each object represents a single COM port. The Name property typically contains the friendly name (e.g., "USB Serial Port (COM3)"), while DeviceID holds the canonical identifier (e.g., "COM3"). The Status field indicates whether the port is operational, which helps filter out disabled or faulty devices.

If you only need the port names for further processing, you can pipe the output to Select-Object -ExpandProperty Name. This simplifies the result into a clean list of strings, making it easier to iterate over in loops or pass to other commands. For example, if you are building a tool that automatically connects to the first available Arduino board, this extraction step is crucial.

Method 2: Reading the Registry

Another reliable technique involves reading the Windows Registry directly. The key HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM contains a mapping of COM port names to their corresponding device paths. This method is particularly useful when WMI queries might be restricted or when you need to verify port assignments at a lower level.

Get-ItemProperty -Path "HKLM:\HARDWARE\DEVICEMAP\SERIALCOMM"

This command retrieves all values within the specified registry key. Each value name corresponds to a COM port (e.g., \Device\Serial0), and the data value is the actual port name (e.g., COM3). You can parse this output to create a hashtable or array of port names. Note that this method may include ports that are currently disconnected but were previously registered, so cross-referencing with WMI data is often recommended for accuracy.

Registry access requires appropriate permissions. Ensure your PowerShell session has administrative rights if you encounter access denied errors. Additionally, some virtual COM ports created by software emulators might not appear in this key, so combining both methods ensures complete coverage of all potential serial interfaces.

Filtering and Validating Ports

Once you have retrieved the list of ports, you may need to filter them based on specific criteria. For instance, you might want to exclude network redirectors or focus only on USB-based adapters. You can achieve this by adding filtering logic to your WMI query or by parsing the Description field in PowerShell.

Get-CimInstance -ClassName Win32_SerialPort | Where-Object { $_.Description -like "*USB*" }

Using CimInstance instead of WmiObject is generally recommended for newer versions of PowerShell, as it offers better performance and interoperability with .NET frameworks. The Where-Object clause allows you to refine the results dynamically. For example, checking for "USB" in the description helps identify virtual serial ports created by FTDI, CP210x, or CH340 chipsets.

Validation is also important. A port listed in WMI might be occupied by another process. To ensure a port is truly available for use, you can attempt to open a System.IO.Ports.SerialPort object in .NET. If the open operation succeeds, the port is free; otherwise, it is in use or inaccessible. This step adds a layer of reliability to automated deployment scripts.

Integrating with Other Scripts

Incorporating COM port enumeration into larger automation workflows can streamline device management. For example, you might combine this functionality with scripts that configure automatic updates or manage task interruptions. Understanding how to reliably detect hardware resources is foundational for any complex Windows administration task. If you are working on broader system configurations, such as Opt in Microsoft Automatic Updates using PowerShell, knowing the state of your system's peripherals ensures that background processes do not interfere with hardware-dependent operations.

Similarly, when dealing with scheduled tasks that might interrupt long-running serial communications, being able to quickly identify and release ports is vital. This knowledge complements techniques for Stopping a Windows 11 PowerShell Script Task in Task Scheduler, allowing you to gracefully handle resource conflicts during maintenance windows.

Frequently Asked Questions

Why does my script show COM ports that are not physically connected?

WMI and Registry queries return all ports configured in the system, including those from disconnected USB adapters or virtual drivers. To find only currently active ports, check the Status property in WMI or attempt to open the port using a .NET SerialPort object.

How can I get the exact device path for a COM port?

The DeviceID property in Win32_SerialPort often contains the device path. Alternatively, reading the HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM registry key provides a direct mapping between the COM name and its underlying device path.

Is there a difference between Get-WmiObject and Get-CimInstance?

Yes. Get-CimInstance uses the CIM/WSMAN protocol and is generally faster and more secure than the legacy Get-WmiObject. It is the recommended cmdlet for PowerShell 3.0 and later versions for querying system information.

Can I use these methods to detect Bluetooth COM ports?

Standard WMI queries for Win32_SerialPort may not always include Bluetooth serial ports, as they are often managed by different drivers. You may need to check the Registry or use specific Bluetooth APIs to enumerate these virtual serial connections.

What should I do if I get an Access Denied error?

Reading certain registry keys or querying WMI classes may require elevated privileges. Run your PowerShell console as Administrator to resolve permission issues. Additionally, ensure that no other application is exclusively locking the port you are trying to inspect.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More