Backup and restore DHCP with Powershell

This is a helpful script for migrating from one DHCP server to another. With this, you can backup and restore DHCP with powershell. Run this script from a Domain controller or any other system that you are logged in as Domain Admin. When you run the script it will ask you the name of the source DHCP server. The leases and scopes from that server will be backed up locally on the system you run this from in a folder called DHCP. You will then be asked if you would like to restore. If you say yes, you will be asked what the destination server name is. It will now restore the scopes and leases you backed up earlier to the destination server. After this completes don’t forget to authorize the new server and de authorize the old one.

### Get source server name from user
$sourceServer = Read-Host "Enter the name of the source DHCP Server"
$choice = "n"

try {
    ###  Create DHCP Folder on local C:\ Drive
    New-Item -Name "DHCP" -ItemType Directory -Path C:\
    ###  Actual export command
    Export-DhcpServer -File "C:\dhcp\$sourceServer.xml" -Leases -Force -ComputerName $sourceServer –Verbose -ErrorAction Stop
    Write-Host "Export complete!"
    ###  Ask user to restore to a new server or not
    $choice = Read-Host "Would you like to restore to a new server? y or (n)"


    if ($choice -eq "y") {
        
        try {
            ###  Get Destination server from user
            $destServer = Read-Host "Enter the name of the destination DHCP Server"
            ###  Actual Import command
            Import-DhcpServer -File "C:\dhcp\$sourceServer.xml" -BackupPath C:\DHCP\ -Leases -ScopeOverwrite -Force -ComputerName $destServer –Verbose -ErrorAction Stop
            Write-Host "Success!  Make sure everything looks good!" -ForegroundColor Green
        }
        catch {
            Write-Host "Restore Failed.  Check your access to the new server and make sure DHCP is installed." -ForegroundColor DarkRed
            Exit
        }
    }


}
catch {
    Write-Host "Backup Failed.  Make sure you have access to the server and that you didnt typo the name" -ForegroundColor DarkRed
    Exit
}
Tagged : /