PowerShell – Set DHCP DNS or Set Static DNS


function Set-DNS([string]$EnableDHCP,[string]$dns1, [string]$dns2){
$saNetAdapters = Get-NetIPInterface | Where-Object {$_.ConnectionState -eq "Connected"} 

foreach ($sNetAdapter in $saNetAdapters.ifIndex)
    if ($EnableDHCP -eq "eDHCP")
       Set-DnsClientServerAddress -InterfaceIndex $sNetAdapter -ResetServerAddresses
    Set-DnsClientServerAddress -InterfaceIndex $sNetAdapter -ServerAddresses ($dns1, $dns2)

function Get-NetworkInformation(){
$computer = $env:computername

try {
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer -EA Stop | ? {$_.IPEnabled}
   } catch {
        Write-Warning "Error occurred while querying $computer."
   $array = @()
   foreach ($Network in $Networks) {
    $NetworkAdapter = $Network.Description
    $IPAddress  = $Network.IpAddress[0]
    $SubnetMask  = $Network.IPSubnet[0]
    $DefaultGateway = $Network.DefaultIPGateway
    $DNSServers  = $Network.DNSServerSearchOrder
    $WINS1 = $Network.WINSPrimaryServer
    $WINS2 = $Network.WINSSecondaryServer   
    $WINS = @($WINS1,$WINS2)         
    $IsDHCPEnabled = $false
    If($network.DHCPEnabled) {
     $IsDHCPEnabled = $true
    $MACAddress  = $Network.MACAddress
    $OutputObj  = New-Object -Type PSObject
    #$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
    $OutputObj | Add-Member -MemberType NoteProperty -Name NetAdapter -Value $NetworkAdapter
    $OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
    $OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
    $OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value ($DefaultGateway -join ",")      
    #$OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled
    $OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value ($DNSServers -join ",")     
    #$OutputObj | Add-Member -MemberType NoteProperty -Name WINSServers -Value ($WINS -join ",")        
    $OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress -Value $MACAddress
    $array += $OutputObj
   $array | Format-Table -AutoSize


Write-Output "Current Network Information"

# Enable DHCP DNS
#Set-DNS "eDHCP"

# Set Static DNS
#Set-DNS "dDHCP" "" ""

Set-DNS "$1" "$2" "$3"

Write-Output "Updated Network Information"

Execute with

.\ChangeDNS.ps1 "eDHCP"
.\ChangeDNS.ps1 "dDHCP" "" ""
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.