Home > database >  Powershell - Get only the COM port number
Powershell - Get only the COM port number

Time:01-31

Can anyone advise on how to extract / get the COM value from this Powershell code:

Get-WMIObject Win32_PnPEntity | where {$_.Name -like "Standard Serial over Bluetooth link*" -AND $_.DeviceID -like "*AB9078566C8A*"} |
>>       Format-Table Name

The Output as the moment is:

Name
----
Standard Serial over Bluetooth link (COM10)

I want to get only:

10

CodePudding user response:

Use regex.

$a = "Standard Serial over Bluetooth link (COM10)"
$a -match '\d '
$matches[0]
10

CodePudding user response:

How about this? % is a shortcut for foreach-object. \d is regex for numbers. Matches is an object property output by select-string, and value is a property inside matches.

Get-WMIObject Win32_PnPEntity | 
  where {$_.Name -like 'Standard Serial over Bluetooth link*' -AND 
  $_.DeviceID -like '*AB9078566C8A*'} | 
  select-string \d  | % { $_.matches.value }

10

I tested it like this:

[pscustomobject]@{name='Standard Serial over Bluetooth link (COM10)'} |
  select-string \d  | % { $_.matches.value }

10
  •  Tags:  
  • Related