The following PowerShell script can be used to back up all the DHCP Servers in a domain.
$LogDate = (Get-Date -Format "yyyy-MM-dd")
$dhcpServers = Get-ADObject -SearchBase 'CN=NetServices,CN=Services,CN=Configuration,DC=contoso,DC=com' -Filter * -Properties dhcpIdentification | Where-Object {$_.dhcpIdentification -eq "DHCP Server object"}
Foreach ($dhcpServer in $dhcpServers)
{
If (Test-Connection $dhcpServer-ErrorAction SilentlyContinue -Count 1)
{
$RemoteDirectory = "\\$dhcpServer\C$\Windows\System32\dhcp\backup"
$LocalDirectory = "C:\Data\DHCPBackup\$dhcpServer"
Try
{
Backup-DhcpServer -ComputerName $dhcpServer-Path "C:\Windows\system32\dhcp\backup"
robocopy $RemoteDirectory "$LocalDirectory\backup" *.* /e /zb /xjd /r:5 /w:5 /mir /log+:"C:\data\DHCPBackup\$LogDate.log"
}
Catch
{
Send-MailMessage -SmtpServer "emailrelay.contoso.com" `
-to "Me@contoso.com" `
-from "Blackhole@contoso.com" `
-Subject "Failed to back up DHCP: $dhcpServer"
}
Try
{
If(!(Test-Path "$LocalDirectory\export"))
{
New-Item "$LocalDirectory\export" -Type directory
}
Export-DhcpServer -ComputerName $DHCPServer -File "$LocalDirectory\export\$dhcpServer.xml" -Force
}
Catch
{
Send-MailMessage -SmtpServer "emailrelay.contoso.com" `
-to "me@contoso.com" `
-From "Blackhole@contoso.com" `
-Subject "Failed to export DHCP configuration: $dhcpServer"
}
}
Else
{
Send-MailMessage -SmtpServer "emailrelay.contoso.com" `
-to "me@contoso.com" `
-from "blackhole@contoso.com" `
-Subject "Unable to reach DHCP Server: $dhcpServer"
}
}
Leave a Reply