Sneh Shah
Sneh Shah

Reputation: 164

Adding a route on Windows machine for a specific adapter using powershell

I am working on a Windows Server will multiple adapters. The primary adapter has a default gateway. Now I need to setup a gateway (Not Default gateway) for the secondary adapter. Generally I would use a route add command for that specific adapter for which I need to Interface ID which I get by typing the "route print".

However I am not able to find any way to find the Interface ID of the adapter programmatically. Any options?

Upvotes: 0

Views: 1308

Answers (2)

Frode F.
Frode F.

Reputation: 54941

You can get the InterfaceIndex using either Win32_NetworkAdapter or Win32_NetworkAdapterConfiguration WMI-class. I would use Win32_NetworkAdapterConfiguration as you could filter on IPEnabled and DefaultIPGateway to find the active network adapter with no default gateway. Ex:

#Get enabled network adapters
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 1" |
#With no default gateway or no IPv4 default gateway
Where-Object { $_.DefaultIPGateway -eq $null -or (@($_.DefaultIPGateway -match '\d+\.\d+\.\d+\.\d+').Count -eq 0)  } |
Format-Table Caption, InterfaceIndex, IPEnabled, {$_.IPAddress[0]}

Caption                                                  InterfaceIndex IPEnabled $_.IPAddress[0]
-------                                                  -------------- --------- ---------------
[00000002] D-Link DWA-140 Wireless N USB Adapter(rev.B3)              2      True 192.168.1.5  

#Get interfaceindex
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 1" |
Where-Object { $_.DefaultIPGateway -eq $null -or (@($_.DefaultIPGateway -match '\d+\.\d+\.\d+\.\d+').Count -eq 0)  } |
Select-Object -ExpandProperty InterfaceIndex

2

You could probably add the route using Win32_IP4RouteTable or Win32_IP4PersistedRouteTable but it's probably easier to just use route add and use WMI only to get the InterfaceIndex

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174815

You can use the Get-NetIPInterface cmdlet to retrieve all interfaces. The ifIndex property will have the ID you're looking for.

Once you've found the index or alias of the desired interface, use New-NetRoute to add the route


Prior to Windows Server 2012, use netsh or the route command

Upvotes: 1

Related Questions