Link to home
Start Free TrialLog in
Avatar of hcca
hcca

asked on

Use Powershell to Set DNS servers unless already null

I found a handy PowerShell script that will change the DNS servers to specified values. I'll paste it below. However, it is too efficient. A number of my servers use multiple NICs for iSCSI and have, by intent, no DNS addresses in their IP4 configuration. Is there a way to modify this script so it acts only on adapters which currently have a value set for the DNS resolver?
$servers = get-content "c:\scripts\computers.txt"
#$servers = "SERVERA","SERVERB","CLIENT1"
get-credential 
foreach($server in $servers) {
Write-Host "Connect to $server..."
$nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE"}
$newDNS = "10.241.0.54","10.253.63.102"
 
foreach($nic in $nics) {
Write-Host "`tExisting DNS Servers " $nic.DNSServerSearchOrder
$x = $nic.SetDNSServerSearchOrder($newDNS)
 
if($x.ReturnValue -eq 0) {
Write-Host "`tSuccessfully Changed DNS Servers on " $server
} else {
Write-Host "`tFailed to Change DNS Servers on " $server
}
}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hcca
hcca

ASKER

Fantastic! That worked perfectly. I was attempting the same thing but my limited PowerShell abilities had me forgetting the - in front of and.