1

I am very new to powershell and am trying to extract a number from a variable. For instance, I get the list of ports using this command: $ports = [system.io.ports.serialport]::getportnames()

The contents of $ports is: COM1, COM2, COM10, COM16 and so on.

I want to extract the numbers from $ports. I looked at this question. It does what I want, but reads from a file.

Please let me know how to resolve this.

Thanks.

Edit: I was able to do what I wanted as follows:

 $port=COM20

 $port=$port.replace("COM","")

But if there is any other way to do this, I will be happy to learn it.

3 Answers 3

4

Well, a quick way would be

$portlist = [System.IO.Ports.SerialPort]::GetPortNames() -replace 'COM'

If you want it to be a list of integers and not numeric strings, then you can use

[int[]] $portlist = ...
Sign up to request clarification or add additional context in comments.

Comments

2

Something like this should work:

# initialize the variable that we want to use to store the port numbers.
$portList = @()

# foreach object returned by GetPortNames...
[IO.Ports.SerialPort]::GetPortNames() | %{
    # replace the pattern "COM" at the beginning of the string with an empty
    # string, just leaving the number.  Then add the number to our array.
    $portList += ($_ -ireplace "^COM", [String]::Empty)
}

Note that I used [IO.Ports.SerialPort] instead of [System.IO.Ports.SerialPort]. These are the same things - PowerShell implicitly assumes that you're working with the [System] namespace, so you don't need to specify it explicitly, though there's nothing wrong with doing it.

Edit To answer your questions:

%{...} is shorthand for foreach-object {...}.

$_ indicates the object that is currently in the pipeline. When we're inside a foreach-object block, $_ resolves to the one object out of the entire collection that we're currently dealing with.

If we write my code a bit differently, I think it'll be easier to understand. Between these examples, $_ and $port are the same things.

$portList = @()
foreach ($port in [IO.Ports.SerialPorts]::GetPortNames()) {
    $portList += ($port -ireplace "^COM", [String]::Empty)
}

Hope that helps!

2 Comments

Awesome. Thanks. I have 2 follow-up questions: 1. What is the use of %{} and 2. what does $_ mean?
% is an alias for foreach or foreach-object so %{} = for each item passed into the pipeline, do what's inside the curly braces. And $_ refers to the current object in the pipeline, in this case the current line/port being inspected
1

This should cover it:

$portnos = $ports | foreach {$_ -replace 'COM',''}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.