Sarvavyapi
Sarvavyapi

Reputation: 850

Extract number from a variable in powershell

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.

Upvotes: 1

Views: 1174

Answers (3)

mikekol
mikekol

Reputation: 1862

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!

Upvotes: 2

Graham Gold
Graham Gold

Reputation: 2485

This should cover it:

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

Upvotes: 1

Joey
Joey

Reputation: 354804

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 = ...

Upvotes: 4

Related Questions