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"
foreach($server in $servers) {
Write-Host "Connect to $server..."
$nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE"}
$newDNS = "",""
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

Who is Participating?
I've faced essentially the same situation before.
You can change line 6 to
$nics = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $server -ErrorAction Inquire | Where{$_.IPEnabled -eq "TRUE" -and $_.DnsServerSearchOrder -ne $null}

Open in new window

hccaAuthor Commented:
Fantastic! That worked perfectly. I was attempting the same thing but my limited PowerShell abilities had me forgetting the - in front of and.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.