Get active network adapter and set DNS via PowerShell
On Windows 10, I need to manually set my DNS server immediately after login. For some reason It seems DHCP blows away my manual settings on each reboot. :-( )
I vary between using wifi and a cable (depending on whether I am at desk with dock).
This command works great:
Set-DNSClientServerAddress –interfaceIndex 25 –ServerAddresses (“127.0.0.1”,”1.1.1.2”)How do I dynamically figure out the interfaceIndex for the currently active network connection?
SOLUTION
This is a work in progress (haven't figured out all the variations to look for the right adapter when on dock, etc) but it works on wifi (I have multiple vmware interfaces that are Up, need to filter them out!)
$adapterIndex = Get-NetAdapter | % { Process { If (( $_.Status -eq "up" ) -and ($_.Name -eq "Wi-Fi") ){ $_.ifIndex } }};
Set-DNSClientServerAddress –interfaceIndex $adapterIndex –ServerAddresses (“127.0.0.1”,”1.1.1.2”); 2 1 Answer
Use get-netadapter and get the value of the currently "active" network adapter per the status value of "up". Get the index value of that adapter dynamically using that value. Then use that as the value for the index in the Set-DNSClientServerAddress command to set the DNS addresses.
Please read more about the conditional logic and other techniques used to help get this detail dynamically in the Supporting Resources section.
PowerShell
[int]$intix = Get-NetAdapter | % { Process { If ( $_.Status -eq "up" ) { $_.ifIndex } }};
Set-DNSClientServerAddress –interfaceIndex $intix –ServerAddresses ("127.0.0.1","1.1.1.2");Get-NetAdapter (Output Example)
Note: Notice below that the ifIndex value 7 for the Wi-Fi named adapter is active and up.
Name InterfaceDescription ifIndex Status MacAddress LinkSpeed
---- -------------------- ------- ------ ---------- ---------
Bluetooth Network Conn... Bluetooth Device (Personal Area Netw... 20 Disconnected 98-5F-D3-4B-59-C4 3 Mbps
Ethernet 3 Some Virtual Ethernet Adapter 14 Disabled 02-50-41-00-00-01 2 Gbps
Wi-Fi Marvell AVASTAR Wireless-AC Network ... 7 Up 98-5F-D3-4B-59-C3 468 Mbps
Ethernet 2 Cisco AnyConnect Secure Mobility Cli... 4 Not Present 00-05-9A-3C-7A-00 0 bpsSupporting Resources
- Get-NetAdapter
- ForEach-Object
Standard Aliases for Foreach-Object: the '
%' symbol, ForEach - If()
More in general
"Zoraya ter Beek, age 29, just died by assisted suicide in the Netherlands. She was physically healthy, but psychologically depressed. It's an abomination that an entire society would actively facilitate, even encourage, someone ending their own life because they had no hope. Th…"