2017-12-18 80 views
1

我想使用powershell腳本獲取默認gatway,我可以得到它如下。PowerShell腳本值提取

Get-WmiObject -Class Win32_IP4RouteTable | 
    where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} | 
     Sort-Object metric1 | select nexthop | select-object -first 1 

結果

nexthop 
------- 
0.0.0.0 

但是我想只獲取值 「0.0.0.0」,而不是頭,這方面的任何解決方案?

+0

你應該得到的屬性值。 –

回答

1

您應該使用以下任一腳本獲取屬性值。

使用(your script).PropertyName

(Get-WmiObject -Class Win32_IP4RouteTable | 
    where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} | 
     Sort-Object metric1 | select nexthop | select-object -first 1).nexthop 

或使用使用your script | select -ExpandProperty PropertyName

Get-WmiObject -Class Win32_IP4RouteTable | 
    where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} | 
     Sort-Object metric1 | select nexthop | select-object -first | 
      select -ExpandProperty nexthop 
+0

**注:**答案是一般的,並顯示如何獲得物業的價值。一般情況下,[Vincent](https://stackoverflow.com/a/47863981/3110834)也提到過,最好不要多次使用select-object,如果使用單個select-object可以實現相同的結果。 –

1

您不必使用選擇對象cmdlet多的時間。

Get-WmiObject -Class Win32_IP4RouteTable -Filter "Destination = '0.0.0.0' AND Mask = '0.0.0.0'" |  
     Sort-Object metric1 | Select-Object -First 1 -ExpandProperty nexthop 

(Get-WmiObject -Class Win32_IP4RouteTable -Filter "Destination = '0.0.0.0' AND Mask = '0.0.0.0'" |  
     Sort-Object metric1 | Select-Object -First 1).nexthop