Backup all Active Directory authorised DHCP Servers
Use the following VBScript code to interrogate Active Directory for a list of all authorised DHCP Servers which are then piped to a Net Shell (NETSH) backup command. See below for the up-to-date PowerShell version.
The backups are (usually) created in C:\DHCP_BACKUPS and this folder must exist prior to executing the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
'========================================================== ' Author: Lewis Roberts ' ' Date: 13/01/2012 ' ' Description: Automates the backup of all "authorised" ' DHCP Servers listed in the Active Directory using ADO ' (to obtain the list of authorised servers) ' and NETSH (to perform the actual backup) ' '=========================================================== 'On Error Resume Next Set oSh = CreateObject("WScript.Shell") ' Instantiate a Shell Object Set oFS = CreateObject("Scripting.FileSystemObject") ' Instantiate a File System Object Set oSystem = oSh.Environment("PROCESS") oSystemDrive = oSystem("SYSTEMDRIVE") sBackupLocation = oSystemDrive & "\DHCP_BACKUPS" If Not oFs.FolderExists(sBackupLocation) Then oSh.Popup "The backup folder : " & sBackupLocation & " does not exist!" & vbLf & vbLf &_ "Please create this folder before running this script again.", 0, "DHCP Server Backup", 0 + 16 + 2048 WScript.Quit End If ADSRoot = "CN=Configuration,DC=domain,DC=com" Const ADS_SCOPE_SUBTREE = 2 Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = "SELECT * FROM 'LDAP://" & ADSRoot & "' WHERE objectClass='dHCPClass' ORDER BY DisplayName" Set objRecordSet = objCommand.Execute objRecordSet.MoveFirst Do Until objRecordSet.EOF strADPath = LCase(objRecordSet.Fields("adsPath").Value) Set oDHCPServer = GetObject(objRecordSet.Fields("adsPath").Value) oServer = oDHCPServer.cn If Not oServer = "DhcpRoot" Then oSh.Popup "Processing DHCP Server: " & oServer, 1, "DHCP Backup", 0 + 2048 + 4096 StrCommand = "CMD /C NETSH DHCP SERVER \\" & oServer & " DUMP > """ & sBackupLocation & "\" & oServer & "_DHCP_CONFIG.TXT""" oSh.Run strCommand End If Set oDHCPServer = Nothing objRecordSet.MoveNext Loop WScript.Quit |
Let me know if you have any issues!
– Lewis
EDIT: I brought this script in to the PowerShell world with the following script. It adds a chunk of error checking and event logging etc which you can choose to get rid of if you so wish.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
Import-Module ActiveDirectory -ErrorAction Stop #===========# # Variables # #===========# # Event source for event log entries $EventSource = "DHCPBackupScript" # The location where GPO backups will be saved. $BackupLocation = "C:\DHCPBackups" # Delete backups older than...days $ArchiveAge = 90 # Get the domain and configuration containers $RootDSE = [ADSI]"LDAP://RootDSE" $Config = $RootDSE.Get("configurationNamingContext") $FormatDate = (Get-Date -Format yyyyMMdd-HHmmss).ToString() #===================# # Script Processing # #===================# try { $SourceExists = [System.Diagnostics.EventLog]::SourceExists($EventSource) } catch [System.Management.Automation.MethodInvocationException] { $SourceExists = $false } If (!$SourceExists) { Write-Host "Can't find the event source to log events under." -ForegroundColor "Red" Write-Host "Please register the event source `"$EventSource`" before executing this script." -ForegroundColor "Red" Write-Host "`v`teg. New-EventLog -source $EventSource -logname Application" -ForegroundColor "Red" $Error.Clear() Exit } If (!(Test-Path $BackupLocation)) { Write-Host "Unable to access `"$BackupLocation`". Please ensure this location is available before continuing." -ForegroundColor "Red" Write-EventLog -LogName Application -Source $EventSource -EventId 2002 -EntryType Error -Message "Unable to access `"$BackupLocation`". Please ensure this location is available before continuing." -Category $false Exit } $DHCPServers = Get-ADObject -Filter '(objectClass -eq "dHCPClass") -and (Name -ne "DhcpRoot")' -SearchBase $Config ForEach ($DHCPServer in $DHCPServers) { $DHCPServerName = $DHCPServer.Name.ToString() Write-Host "Backing up DHCP Server `"$DHCPServerName`"" -ForegroundColor Green Write-EventLog -LogName Application -Source $EventSource -EventId 2001 -EntryType Information -Message "Backing DHCP Server:`v`t$DHCPServerName`nto`v`t$BackupLocation\$DHCPServerName-$FormatDate.txt" -Category $false $dumpFile = NETSH DHCP SERVER \\$DHCPServerName DUMP $Check = Select-String -InputObject $dumpFile -Pattern "Configuration Information for Server $DHCPServerName" If ($Check) { $dumpFile | Out-File "$BackupLocation\$DHCPServerName-$FormatDate.txt" } Else { Write-Host "Backup of DHCP Server `"$DHCPServerName`" FAILED!" -ForegroundColor Red Write-EventLog -LogName Application -Source $EventSource -EventId 2002 -EntryType Error -Message "Backup of DHCP Server `"$DHCPServerName`" failed.`nOutput from dump command:`v`t$dumpFile" -Category $false } } # Clean up old files $Files = Get-ChildItem $BackupLocation | Where {$_.LastWriteTime -le (Get-Date).AddDays(-$ArchiveAge)} If ($Files) { $Files | % { $Deleted += $_.Name+"`n" Remove-Item $_.FullName -force } Write-EventLog -LogName Application -Source $EventSource -EventId 2003 -EntryType Warning -Message "Deleted following DHCP Backup files older than $ArchiveAge days:`v$Deleted" -Category $false } |
Wow Lewis awesome script! I edited slightly to backup to a network share. Curious, looking at the backup file that it creates, I don’t see any reference to existing leases. Does this not do that? I am going to set up a test dhcp server to test the restore but i awesome you just restore this file that is created through the restore wizard?
many thx for the cool script
Hmm, strange, it should back up reservations but no, it doesn’t back up leases. They are after all “dynamic” so it shouldn’t matter. The clients themselves will actually request the same address from the DHCP server if it has a pre-existing lease though so it may not be an issue.
A quick word of warning though – make sure you edit the DUMP files to direct the restored config to the correct target server! The DUMP files include the name of the DHCP server from which it was backed up so that you can just run it through netsh without modification.
I’ve actually since updated this script to PowerShell v2 and added notifications and event logging if you’re interested.
Tom, see a previous post of mine to see how to use the backup script.
http://www.lewisroberts.com/2011/07/16/quickly-back-up-your-windows-server-dhcp-configuration/
NB: Remember to edit the output for the new server before running it through netsh!
Hi Lewis,
I am getting the below error when executing the script i.e. error in Line 44. I am not familiar with vb scripting. Can you help me?
C:\dhcpback.vbs(44, 1) Active Directory: A referral was returned from the server
You must make sure you run the script using a user account that has permissions to read the DHCP database (DHCP Admins) and as someone that can query the relevant portions of Active Directory (any domain account should permit this).
Let me know how you get on.
-Lewis
I am executing the script with Domain Admin privileges
Could be the ever helpful UAC getting in the way.
Start a Command Prompt as Administrator (right-click, Run as Admin) and then run the script using: cscript C:\Backupscript.vbs
-Lewis
That is the way I am executing the script
OOPS Apologies Lewis… I forgot to modify the script to include my domain name… Now it is working perfect..Brilliant..Thank you
Ah, yeah, that would do it. 🙂
The PowerShell one automatically gets the domain name and location of the Configuration container so you could use that 🙂
-Lewis
The created dumpfile doesn’t include DHCP policies. Do you know a way to complete the complete dhcp database?
Hi Christof, the above script is ageing now but it generally covered everything required in 2003 – 2012. It has been some time since I looked at a 2012 DHCP Server so I’m not sure where policies would be kept. With 2012 R2 I believe the NETSH DHCP command was removed from Net Shell since Microsoft want you to use PowerShell.
If you’re backing up 2012R2, look in to Export-DhcpServer (https://technet.microsoft.com/en-us/library/jj590659.aspx) instead. It may be that policies aren’t backed up as part of either Netsh (2003-2012) or Export-DhcpServer for 2012R2. Sorry!
Hi Lewis, My Name is Ameer.. just wanted to check with you on the possibilities of adding a reporting functionality to this script. it would be great if the script can send an HTML report with list of servers backup successfully and also failed..
just a thought..
Hello,
I tried Powershell Script but getting below error,
Backing up DHCP Server “**********”
Backup of DHCP Server “*******” FAILED!
Write-EventLog : Cannot validate argument on parameter ‘Message’. The character length of the 333120 argument is too
long. Shorten the character length of the argument so it is fewer than or equal to “32766” characters, and then try the
command again.
At C:\DHCPBackups\DHCPBackup.ps1:60 char:106
+ Write-EventLog -LogName Application -Source $EventSource -EventId 2002 – …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Write-EventLog], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WriteEventLogCommand
Hi Lewis,
I am using powershell version 5 on Windows 2016 Server and when I run the script, I get the below error:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\Backup-Authorized-DHCP-Servers.ps1
Can’t find the event source to log events under.
Please register the event source “DHCPBackupScript” before executing this script.
eg. New-EventLog -source DHCPBackupScript -logname Application
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How to resolve this