2017-07-17 54 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'產生一個對象(實際上是一個對象列表)。然後,「選擇對象」提取所述列表的第一個對象的一個​​屬性的值。 –

相關問題