Get active network adapter and set DNS via PowerShell
Solution 1:
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 bps
Supporting Resources
- Get-NetAdapter
-
ForEach-Object
Standard Aliases for Foreach-Object: the '
%
' symbol, ForEach - If()