murtdoc
murtdoc

Reputation: 3

Powershell - Get only the COM port number

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

UPDATE:

Thanks to @js2010 I was able to get the COM port number from PowerShell. If someone can Upvote his answer, I would appreciate it. I don't have enough rep to do that, atm. The final code is:

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

Upvotes: 0

Views: 2257

Answers (2)

js2010
js2010

Reputation: 27428

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*'} | 
  % name | select-string \d+ | % { $_.matches.value }

10

I tested it like this:

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

10

Upvotes: 1

navylover
navylover

Reputation: 13539

Use regex.

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

Upvotes: 0

Related Questions