PowerShell脚本值提取
问题描述:
我想使用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”,而不是头,这方面的任何解决方案?
答
您应该使用以下任一脚本获取属性值。
使用(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可以实现相同的结果。 –
答
您不必使用选择对象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
你应该得到的属性值。 –