Powershell – How to receive email notification of non-AD joined DHCP leases

active-directorydhcppowershellpowershell-v4.0windows-server-2012

This answer to theCleaner's question helped me some Windows DHCP Server – get notification when a non-AD joined device gets an IP address but the answer to his question involved Quest Poweshell cmdlets. I would like to achieve a solution with plain old Powershell v4 cmdlets.

Problem

I currently receive no notification of new DHCP leases at all. I would like to receive notifications when someone plugs into one of our jacks here, gets a DHCP lease from our Windows Server 2012 DHCP server, but hasn't been AD-joined. So I want an email notification of new DHCP leases for non-AD joined devices.

What I've tried

I have put together some Powershell code, borrowing some from theCleaner's question mentioned above.

 Get-DhcpServerv4Lease -allleases -ScopeId #myscopeIDhere | Select-Object @{expression= {$_.hostname}; label='name' } | export-CSV -notypeinformation C:\dhcp\LeaseLog.csv

import-module activedirectory

#get input CSV

$leaselogpath = "c:\DHCP\LeaseLog.csv"
Import-csv -path $leaselogpath | 
#query AD for computer name based on csv log
foreach-object `
{ 
   $NameResult = Get-ADComputer -Filter * 
   If ($NameResult -eq $null) {$RogueSystem = $_.name}
   $RogueSystem | Out-File C:\DHCP\RogueClients.txt -Append
   $RogueSystem = $null

}
Get-Content C:\DHCP\RogueClients.txt | Select-Object -Unique | Out-File C:\DHCP\RogueClientsFinal.txt
Remove-Item C:\DHCP\RogueClients.txt

#send email to sysadmin
$smtpserver = #my email server IP address here
$from="abcd@abcdefg.com"
$to="sysadmin@abcdefg.com"
$subject="Non-AD joined DHCP clients"
$body= (Get-Content C:\DHCP\RogueClientsFinal.txt) -join '<BR>&nbsp;<BR>'
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)

I receive the email "Non-AD joined DHCP clients" but there are no objects in the email. We do have non-AD joined DHCP leases (I connected a non-AD laptop the network for testing), but the laptop doesn't show in the email. I don't receive any red test after running the script either.

If anyone has suggestions please let me know. I obviously have something wrong somewhere in my script. I personally think it might have to do with my AD cmdlets and the CSV import.

Best Answer

$NameResult = Get-ADComputer -Filter *

This query will return all computers in AD, and its result will never be empty; you should query for the actual computer name you are trying to find:

$NameResult = Get-ADComputer $_.Name

Also, the names in the DHCP log files will likely be FQDNs (such as computer.domain.local); if this is the case, you need to strip the domain suffix before feeding them into Get-ADcomputer, which only wants the computer name:

$ComputerName = $_.Name.Replace(".domain.local",$null)
$Result = Get-ADComputer $ComputerName