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.

4

3 回答 3

4

好吧,一个快速的方法是

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

如果您希望它是整数列表而不是数字字符串,那么您可以使用

[int[]] $portlist = ...
于 2013-07-18T21:44:33.330 回答
2

像这样的东西应该工作:

# 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)
}

请注意,我使用[IO.Ports.SerialPort]而不是[System.IO.Ports.SerialPort]. 这些是相同的 - PowerShell 隐含地假定您正在使用[System]命名空间,因此您不需要明确指定它,尽管这样做并没有错。

编辑 回答您的问题:

%{...}是 的简写foreach-object {...}

$_表示当前在管道中的对象。当我们在一个foreach-object块内时,$_解析为我们当前正在处理的整个集合中的一个对象。

如果我们写我的代码有点不同,我认为它会更容易理解。在这些例子之间,$_$port都是相同的东西。

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

希望有帮助!

于 2013-07-18T21:42:49.757 回答
1

这应该涵盖它:

$portnos = $ports | foreach {$_ -replace 'COM',''}
于 2013-07-18T21:46:07.650 回答