NS Change PowerShell Script – Updated!

0

Posted on October 22, 2014 by

Some time ago, I posted a PowerShell script to detect changes in external NS records for domains.  I’ve made some modifications to the script to reduce false positives.  Additionally, the script now emails the “before” and “after” results of the NSLookup command for easy comparison.

Updated script is below:

# Set up variables
$smtp_server = '<YourSMPTServer>'
$to_email = '<email>'
$from_email = '<email>'
$dns_server = "<YourExternalDNSServer>"
$domain = "<YourDomain>"
$nslookup_args = "-type=ns $domain $dns_server | sort.exe >domain.new.txt"
$nslookup_cmd = "nslookup.exe $nslookup_args"

Invoke-Expression $nslookup_cmd

if (Test-Path .\domain.old.txt)
{
    $ns_obj_new = Get-Content .\domain.new.txt | Select-String "nameserver"
    $ns_obj_old = Get-Content .\domain.old.txt | Select-String "nameserver"
    if ($ns_obj_new -ne $null -and $ns_obj_old -ne $null)
    {
        $diff_results = Compare-Object $ns_obj_new $ns_obj_old
    }
    else
    {
        $diff_results = $true
    }
}

if ($diff_results)
{
    $evt_message = Get-Content .\domain.new.txt | Out-String
    Write-EventLog -LogName Application -EventId 9000 -EntryType Error -Source "NS Checking Script" -Message $evt_message
    Send-MailMessage -To $to_email -From $from_email -SmtpServer $smtp_server -Attachments .\domain.new.txt, .\domain.old.txt -Subject "ALERT! Change in NS Records" -Body "A change has been detected in the NS records for $domain.`n`n`tACTION REQUIRED!`n`nVerify that this change was authorized."
}

Remove-Item .\domain.old.txt
Rename-Item .\domain.new.txt .\domain.old.txt

As before, change the values in RED, save as a PS1 file, and run as a scheduled task. In order for the script to write to the event log with Event ID 9000, you will need to run the following PowerShell command once on the server:

New-EventLog -Source “NS Checking Script” -LogName Application

Leave a Reply

Your email address will not be published. Required fields are marked *