If you have ever had a need to install multiple NICs onto a Windows machine, or use a Virtual Technology like Virtual Box, it can be difficult to determine your local network IP address because of all the logical network interfaces. It is easy enough to run the ipconfig /all command and see the results but to determine which IP address is being used to access remote networks by using a script requires a little work.
The best approach I could come up with was to use the Windows routing table. If you run the "route print" command on a Windows machine you will see the default network interface that is being used to route traffic to remote networks. Using this information you can determine which IP address is being used as the source address when accessing remote networks.
I had a need to detect the local subnet on a Windows 7 machine and came up with the below script. It will return a PSCustomObject populated with the active network interfaces details.
Using three WMI classes being Win32_IPv4RouteTable, Win32_NetworkAdapter, and Win32_NetworkAdapterConfiguration I could determine the information I was after.
Firstly I retrieved the Windows routing table filtered to the default routes. This gets sorted by the metric and I select the route with the lowest metric. This gave me the InterfaceIndex of the active network interface. Using this index number I could retrieve the network adapter and its configuration.
To use this script either copy the text below into a new function or, as I do, copy it into a ps1 file saved in your path and call the file directly. Here is the Gist link: https://gist.github.com/grantcarthew/7000687