Get IP address of the Network Adapter of a computer having No gateway

16.3k views Asked by At

I've a project to add persistent routes on a list of servers which I need to do through Powershell. Our environment has 2 NIC's for every server , one production one backup. For this I need to fetch the Backup IP address of the computer , replace the last octet by 1 and use it in the 'route add' command. The only way I can think to identify the Backup NIC is to identify the NIC which has No Gateway (Prod NIC has a Default Gateway while Backup NIC doesn't has any). Hence my first step is to identify the Static IPAddress of that NIC which has NO Gateway i.e Default Gateway part is empty however Static IP and Subnet Mask is there. I've tried the following till now with no luck:

Get-WmiObject win32_NetworkAdapterConfiguration -Filter DefaultIPGateway=NULL | Select IPAddress

ERROR - Get-WmiObject : Invalid Query

Get-WmiObject win32_NetworkAdapterConfiguration -Filter DefaultIPGateway="" | Select IPAddress

ERROR - Get-WmiObject : Invalid Query

Also I tried the following code which logically came to my mind:

$ntwk=Get-WmiObject win32_NetworkAdapterConfiguration | Select IPAddress,DefaultIPGateway
forearch($net in $ntwk) 
{
 if($net.DefaultIPGateway -eq "")
 {
  Write-Output "IP of NIC with NO gateway is: "$net.IPAddress
 }
}

ERROR - Get-WmiObject : Invalid Query

Can Someone please help me out as how can I achieve this? Hope I'm clear with my query. Thanks in advance!

3

There are 3 answers

3
Vesper On BEST ANSWER
$configs=gwmi win32_networkadapterconfiguration | where {$_.ipaddress -ne $null -and $_.defaultipgateway -eq $null}
if ($configs -ne $null) { $yourtargetIP= $configs[0].IPAddress[0] }
# $yourtargetIP will have the IP address to make the gateway from

In fact, should you have more than one IPv4 address on your network card, $configs[0].IPAddress will have them all, one by one. More, you can assign two different IP addresses on a single network adapter. So, this will need to be tailored should you find such a server in your organization, but will work correctly if all your network adapters have a single IPv4 address.

1
Manuel Batsching On

You have not specified which PowerShell version you are using. If you are lucky enough to have PowerShell 4.0, you may also use Get-NetIPConfiguration:

Get-NetIPConfiguration | where {$_.IPv4DefaultGateway -eq $null }
1
Sagar Jadhav On

Get-NetIPConfiguration |select IPv4Address, InterfaceAlias