Search code examples
azureazure-powershellazure-backup-vault

Restore-AzRecoveryServicesBackupItem cmdlet to Restore As Files


I have a requirement to (as part of an automation) grab the latest full backup from a Recovery Services vault and "Restore as Files" it (see screenshot below) before moving it to a different subscription for ... restoration?

I want to automate this action:

enter image description here

The Restore-AzRecoveryServicesBackupItem seems to fit the bill, but can't figure out how to configure it to restore the files, rather than the database. Example 7 is almost there, but not quite.


Solution

  • Overview of the procedure is as follows:

    1. Get the vault via Get-AzRecoveryServicesVault
    2. Get the backup item via Get-AzRecoveryServicesBackupItem
    3. Get the recovery point via Get-AzRecoveryServicesBackupRecoveryPoint
    4. Get the container to restore it to via Get-AzRecoveryServicesBackupContainer
    5. Build a configuration for the restore job via Get-AzRecoveryServicesBackupWorkloadRecoveryConfig, with the kicker here specifying the -RestoreAsFiles and -FilePath parameters.
    6. Execute the restore via Restore-AzRecoveryServicesBackupItem

    Full script:

    $vaultName = ""
    $backupItemName = ""
    $sourceServerName = ""
    $restorePath = ""
    
    $vault = Get-AzRecoveryServicesVault -Name $vaultName
    $backupItem = Get-AzRecoveryServicesBackupItem -BackupManagementType AzureWorkload -WorkloadType MSSQL -VaultId $vault.ID -Name $backupItemName -ProtectionStatus Healthy | where-object {$_.ServerName -eq $sourceServerName }
    $latestFullRP = Get-AzRecoveryServicesBackupRecoveryPoint -Item $BackupItem -StartDate ((Get-Date).AddDays(-3)).ToUniversalTime() -EndDate (Get-Date).ToUniversalTime() -VaultId $vault.ID | Sort-Object -Descending -Property RecoveryPointTime | Select-Object -First 1
    $container = Get-AzRecoveryServicesBackupContainer -ContainerType AzureVMAppContainer -VaultId $Vault.Id | Where-Object {$_.ServerName -eq $sourceServerName -and $_.HealthStatus -eq 'Healthy'}
    $restoreConfig = Get-AzRecoveryServicesBackupWorkloadRecoveryConfig -RecoveryPoint $latestFullRP -TargetItem $Target -TargetContainer $Container -RestoreAsFiles -VaultId $vault.ID -FilePath $restorePath
    
    Restore-AzRecoveryServicesBackupItem -WLRecoveryConfig $restoreConfig -ResolveConflict Overwrite -VaultId $vault.ID