Popular Posts

Thursday, August 13, 2020

Get and Set DNS search order using PowerShell

Get DNS

Scenario: I was asked to generate a list of servers that were still using our old DNS servers. This script was included in an SCCM DCM baseline to generate the report.

try{
$isComplaint = $true
$Interface = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “True” -and $_.IPAddress -like "10.*"} -ErrorAction Stop
Foreach($NIC in $Interface) {
$IPs = $NIC.DNSServerSearchOrder
Foreach($IP in $IPs) {
if(($IP -eq 'your.old.DNS.ip') -or ($IP -eq 'your.old.DNS.ip2')) {
$isComplaint = $false
return "Non-Compliant"
}
}
}
if ($isComplaint -eq $true) {
return "Compliant"
}
}
catch{
return "Error"
}




Set DNS

Scenario: Configure new DNS server in DNS search order for those servers still using old DNS server. For this, we created a SCCM task sequence consisting of following script and deployed to a collection of computers. The DNS server list was passed through a TS variable "DNSservers". If you are only intrested about the PowerShell portion, then pass the DNS server list in the following format $DNSServers = “198.168.1.10",”198.168.1.2". The reason why we didnt directly ran the script on all servers was because there were a mixture of domain and workgroup servers that needed this change. We were able to run the script all servers using SCCM without bothering about the connection/authentication challenges.

$logfile = 'C:\Windows\Temp\SetDNS.log'
function writetolog([string] $txt) {
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
Add-content $logfile -value $Stamp':'$txt
}
try{
$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$DNSServers = $tsenv.Value("DNSservers")
write-host "Retrieved DNS servers list successfully"
writetolog("Retrieved DNS servers list successfully : " + $DNSServers)
$DNSServers = $DNSServers -split ','
}
catch{
write-host "Cannot retrieve DNS servers list"
writetolog("Retrieved DNS servers list successfully")
exit -1
}
#$DNSServers = “198.168.1.10",”198.168.1.2"
try{
$Interface = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq “True” -and $_.IPAddress -like "10.*"} -ErrorAction Stop
write-host "Connected to WMI succesfully and interfaces retrieved"
writetolog("Connected to WMI succesfully and interfaces retrieved")
Foreach($NIC in $Interface) {
try{
$NIC.SetDNSServerSearchOrder($DNSServers)
write-host "DNS servers configured successfully"
writetolog("DNS servers configured successfully")
exit 0
}
catch{
write-host "Cannot set DNS servers"
writetolog("Cannot set DNS servers")
exit -1
}
}
}
catch{
write-host "Cannot connect to WMI"
writetolog("Cannot connect to WMI")
return -1
}


 







No comments:

Post a Comment