3

I wanted to fetch default gatway using powershell script and I am able to get it as below.

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

The result

nexthop
-------
0.0.0.0

However I want to fetch only the value "0.0.0.0", not the header, any solution for this ?

1
  • You should get property value. Commented Dec 18, 2017 at 7:19

2 Answers 2

2

You should get property value using either of following scripts.

Using (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

Or by using Using 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
Sign up to request clarification or add additional context in comments.

1 Comment

Note: The answer is general and shows how you can get value of a property. In general, as also mentioned by Vincent, it's better to not use select-object multiple times when you can achieve the same result using a single select-object.
1

You don't have to use Select-Object cmdlet multiple time.

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

or

(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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.