2017-07-17 66 views
3

我想通过PowerShell自动设置一个IP地址,我需要找出我的接口索引号是什么。如何去除变量中除数字之外的所有内容?

什么我已经做了是这样的:

$x = (Get-NetAdapter | 
     Select-Object -Property InterfceName,InterfaceIndex | 
     Select-Object -First 1 | 
     Select-Object -Property Interfaceindex) | Out-String 

这将输出:

 
InterfaceIndex 
-------------- 
      3 

现在的问题,当我尝试用抢仅数:

$x.Trim.('[^0-9]') 

它仍然保留“InterfaceIndex”和下划线。这导致我的脚本的下一部分出错,因为我只需要这个数字。

有什么建议吗?

回答

3

这将让你的工作做好:

(Get-NetAdapter | Select-Object -Property InterfceName,InterfaceIndex | Select-Object -First 1 | Select-Object -Property Interfaceindex).Interfaceindex 

其实你不需要两次选择属性:这样做:

(Get-NetAdapter |Select-Object -First 1| Select-Object -Property InterfceName,InterfaceIndex).Interfaceindex 
+1

或者,将$ x保留为PowerShell对象'$ x = Get-NetAdapter | Select-Object -Property InterfaceName,InterfaceIndex | Select-Object -First 1'并将其引用为'$ x.InterfaceIndex'。 –

+1

你应该总是在左边的 – 4c74356b41

2
(Get-NetAdapter | select -f 1).Interfaceindex 

没有点在选择属性他们在那里默认。如果你想保持物体做:

(Get-NetAdapter | select -f 1 -ov 'variablename').Interfaceindex 

其中f =第一,OV = outvariable

$variablename.Interfaceindex 

你不需要Out-String铸造字符串是隐含的,当你向屏幕输出。如果你尝试使用这些数据进一步下来,PowerShell足够聪明,可以将它从int转换为字符串,反之亦然。

2

回答您的问题直接:您可以删除所有不从,以及变量的数量,消除一切不是数字(或者说位数):

$x = $x -replace '\D' 

然而,更好的形式给出了将根本不加你首先想要删除的内容:

$x = Get-NetAdapter | Select-Object -First 1 -Expand InterfaceIndex 

PowerShell命令通常会产生对象作为输出,所以不是重整这些对象转换为字符串形式,去掉多余的材料,你通常只是扩大p的值您感兴趣的关键属性。

+0

上过滤,不知道这是怎么实现的。在这种情况下$ x = 2(或任何碰巧是界面索引)。所以不是一个真正的对象。 – 4c74356b41

+0

@ 4c74356b41'Get-NetAdapter'产生一个对象(实际上是一个对象列表)。然后,“选择对象”提取所述列表的第一个对象的一个​​属性的值。 –

相关问题