PowerShell/Windows scripting: Get interface name containing a specified gateway IP

StackOverflow https://stackoverflow.com/questions/17461295

  •  02-06-2022
  •  | 
  •  

Question

I'm trying to build a Windows batch script that captures a network interface's name, based on its gateway IP, and then renames the interface. I'm having trouble capturing the interface name, which is a random string. In Windows, I can obtain the needed information by running a piped netsh command:

C:\Users\Administrator>netsh interface ipv4 dump | findstr "nexthop=2.2.2.1"

add route prefix=0.0.0.0/0 interface="Management" nexthop=2.2.2.1 publish=yes

How can I parse for the interface string, as displayed in the output?

I've also tried to experiment in PowerShell using a combination of the following commands, but haven't had much luck. I would appreciate any assistance, or a nudge in the right direction.

 get-wmiObject -Query "select NetConnectionID from Win32_NetworkAdapter"
 get-wmiObject -Query "select DefaultIPgateway from Win32_NetworkAdapterConfiguration"

EDIT: I've started experimenting with wmic. Given the DefaultIPGateway is part of nicConfig, and NetConnectionID is part of nic, is there anyway I can get this working?

wmic nic where "DefaultIPgateway=2.2.2.1" get NetConnectionID
Was it helpful?

Solution

maybe you can use InterfaceIndex to link this objects:

get-wmiObject -Query "select InterfaceIndex from Win32_NetworkAdapter"
get-wmiObject -Query "select InterfaceIndex from Win32_NetworkAdapterConfiguration"

InterfaceIndex Data type: sint32 Access type: Read/write IP address of the next hop of this route. The value in this property is the same as the value in the InterfaceIndex property in the instances of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration that represent the network interface of the next hop of the route. In the case of a route bound to an interface that is realized using a broadcast medium, the value of this field is the agent IP address on that interface. description from: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394162(v=vs.85).aspx

something like this

$index = get-wmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object { ($_.DefaultIPGateway -eq "2.2.2.1") } | Select-object InterfaceIndex
get-wmiObject -Class Win32_NetworkAdapter | Where-Object { ($_.InterfaceIndex -eq $index.InterfaceIndex) } | Select NetConnectionId
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top