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.

The backups are (usually) created in C:\DHCP_BACKUPS and this folder must exist prior to executing the script.


'==========================================================
' 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

This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>