Monday, August 28, 2017

PowerShell Script to send Notification on new dhcp lease

Here is a little powershell script i assembled from different sources to send me an email notifying when there is a new DHCP lease for a computer that is not in the AD




#step 1: get computer names from dhcp
Get-DhcpServerv4Lease -allleases -ScopeId "192.168.X.0" -ComputerName "DHCPSERVERNAME" |
 Select-Object @{expression= {$_.hostname}; label='name' } | export-CSV -notypeinformation C:\temp\dhcp\LeaseLog.csv

$leaselogpath = "c:\temp\DHCP\LeaseLog.csv"
$dhcplist = Import-csv -path $leaselogpath  | ForEach-Object -Process {$_.Name.Replace(".domain.local",$null)}

#step 2: get computer names from AD
import-module activedirectory

$adlist = (Get-ADComputer -filter *).name

#step 3: compare both above lists to find new computer name from dhcp

$comparedlist = (Compare-Object -ReferenceObject $adlist -DifferenceObject $dhcplist ).InputObject

#step 4: compare against static computers in the network

$staticlist = Get-Content C:\temp\DHCP\static.txt
$newdhcp = (Compare-Object $staticlist $comparedlist).InputObject


#step 5: send the email only when there is a new name from all the comparisons
           
if($newdhcp) {           
    #send email to sysadmin
$smtpserver = "SMTPADDRESS"
$from="dhcp@domain.local"
$to="admin@domain.local"
$subject="New Non-AD joined DHCP clients"
$body= "$newdhcp `n
If it is legit, add it to c:\temp\dhcp\static.txt list"
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $false
$mailer.send($msg)           
} else {           
               
}

Some issues with this script:
1. Need to maintain the static.txt list
2. Duplicate names in dhcp will be sent by email as a new lease
3. when computer in the AD is disconnected from the network and dhcp lease expires you will get notification as a new lease

1 comment:

  1. Can I borrow this script? I am gonna use this in my proposal/case study, I'm going to use you as my reference, thank you so much!

    ReplyDelete