This script is used to back up the main MDTDATA partition to a secondary partition (on another drive!) called MDTDATA2. There is only a single, optional parameter:

  • -IncludeVM
    This will include the VM VHDX files (which change a lot and are huge) in the backup. Only do this every so often just so that the disk is relatively recent. It's okay if you have to rebuild the VHDXs.

If the VM is running, it will be stopped and then restarted automatically.

Param([switch]$IncludeVM)

# Configuration settings
$Sources="MDTDATA"
$Dests="MDTDATA2"
$SyncTool='C:\Windows\System32\Robocopy.exe'

# Intro
Write-Host 'We will be synchronizing the backup copy for' $Sources

for ($VolNum = 0; $VolNum -lt $Sources.length; $VolNum++) {
    # Look for the volume
    $SourceVolume = Get-Volume | Where { $_.FileSystemLabel -eq $Sources[$VolNum] }
    if ($SourceVolume.Count -eq 0) {
        Write-Host -ForegroundColor Yellow 'Could not find USB source disk' $Sources[$VolNum]
        Exit
    }
    $SourceLetter = $SourceVolume.DriveLetter
    Write-Host $Sources[$VolNum] 'partition found on drive' $SourceLetter

    $DestVolume = Get-Volume | Where {$_.FileSystemLabel -eq $Dests[$VolNum] }
    if ($DestVolume.count -eq 0) {
        Write-Host -ForegroundColor Yellow 'Could not find USB destination disk' $Dests[$VolNum]
        Exit
    }
    $DestLetter = $DestVolume.DriveLetter
    Write-Host $Dests[$VolNum] 'partition found on drive' $DestLetter
    
    # Make sure VM is stopped
    if ((Get-VM -Name MDT01).State -ne 'Off') {
        $RestartVM = $true
        Write-Host "Stopping the virtual machine"
        Get-Process -Name vmconnect -ErrorAction SilentlyContinue | Stop-Process -Force -Confirm:$false
        Stop-VM -Name MDT01 -Force -Confirm:$false
    }
    
    # Copy content over
    Write-Host 'Starting synchronization to the USB drive...'
    if ($IncludeVM) {
        Start-Process -FilePath $SyncTool -ArgumentList ($SourceLetter + ':\ ' + $DestLetter + ':\ /MIR /SL /XD $Recycle.Bin /XD "System Volume Information"') -Wait -ErrorAction SilentlyContinue -WindowStyle Minimized
    } else {
        Start-Process -FilePath $SyncTool -ArgumentList ($SourceLetter + ':\ ' + $DestLetter + ':\ /MIR /SL /XD $Recycle.Bin /XD "System Volume Information" /XF *.vmdk *.vhd *.vhdx') -Wait -ErrorAction SilentlyContinue -WindowStyle Minimized
    }
    Write-Host
}

if ($RestartVM) {
    Write-Host "Restarting VM"
    Start-VM -Name MDT01 -Confirm:$false
}