使用 PowerShell 备份和恢复 Azure VMBack up and restore Azure VMs with PowerShell

本文介绍如何使用 PowerShell cmdlet 在 Azure 备份恢复服务保管库中备份和还原 Azure VM。This article explains how to back up and restore an Azure VM in an Azure Backup Recovery Services vault using PowerShell cmdlets.

本文介绍如何执行以下操作:In this article you learn how to:

  • 创建恢复服务保管库并设置保管库上下文。Create a Recovery Services vault and set the vault context.
  • 定义备份策略Define a backup policy
  • 应用备份策略以保护多个虚拟机Apply the backup policy to protect multiple virtual machines
  • 对保护的虚拟机触发按需备份作业 在备份(或保护)虚拟机之前,必须完成先决条件中的步骤来准备好保护 VM 的环境。Trigger an on-demand backup job for the protected virtual machines Before you can back up (or protect) a virtual machine, you must complete the prerequisites to prepare your environment for protecting your VMs.

开始之前Before you start

  • 详细了解恢复服务保管库。Learn more about Recovery Services vaults.
  • 查看 Azure VM 备份的体系结构、了解备份过程,以及查看支持、限制和先决条件。Review the architecture for Azure VM backup, learn about the backup process, and review support, limitations, and prerequisites.
  • 查看恢复服务的 PowerShell 对象层次结构。Review the PowerShell object hierarchy for Recovery Services.

恢复服务对象层次结构Recovery Services object hierarchy

下图汇总了对象层次结构。The object hierarchy is summarized in the following diagram.

恢复服务对象层次结构

查看 Azure 库中的 Az.RecoveryServices cmdlet 参考Review the Az.RecoveryServices cmdlet reference reference in the Azure library.

设置和注册Set up and register

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

开始时,请执行以下操作:To begin:

  1. 下载最新版本的 PowerShellDownload the latest version of PowerShell

  2. 键入以下命令查找可用的 Azure 备份 PowerShell cmdlet:Find the Azure Backup PowerShell cmdlets available by typing the following command:

    Get-Command *azrecoveryservices*
    

    这将显示 Azure 备份、Azure Site Recovery 和恢复服务保管库的别名和 cmdlet。The aliases and cmdlets for Azure Backup, Azure Site Recovery, and the Recovery Services vault appear. 下图是你将看到的内容的一个示例。The following image is an example of what you'll see. 它不是完整的 cmdlet 列表。It is not the complete list of cmdlets.

    恢复服务的列表

  3. 使用 Connect-AzAccount -Environment AzureChinaCloud 登录到 Azure 帐户。Sign in to your Azure account using Connect-AzAccount -Environment AzureChinaCloud. 此 cmdlet 打开一个网页,提示输入帐户凭据:This cmdlet brings up a web page prompts you for your account credentials:

    • 也可使用 -Credential 参数将帐户凭据作为参数包含在 Connect-AzAccount -Environment AzureChinaCloud cmdlet 中。Alternately, you can include your account credentials as a parameter in the Connect-AzAccount -Environment AzureChinaCloud cmdlet, using the -Credential parameter.
    • 如果是代表租户的 CSP 合作伙伴,则需使用 tenantID 或租户主域名将客户指定为一名租户。If you are CSP partner working on behalf of a tenant, specify the customer as a tenant, by using their tenantID or tenant primary domain name. 例如:Connect-AzAccount -Environment AzureChinaCloud -Tenant "fabrikam.com"For example: Connect-AzAccount -Environment AzureChinaCloud -Tenant "fabrikam.com"
  4. 由于一个帐户可以有多个订阅,因此请将要使用的订阅与帐户关联在一起:Associate the subscription you want to use with the account, since an account can have several subscriptions:

    Select-AzSubscription -SubscriptionName $SubscriptionName
    
  5. 首次使用 Azure 备份时,必须使用 Register-AzResourceProvider cmdlet 将 Azure 恢复服务提供程序注册到订阅。If you are using Azure Backup for the first time, you must use the Register-AzResourceProvider cmdlet to register the Azure Recovery Service provider with your subscription.

    Register-AzResourceProvider -ProviderNamespace "Microsoft.RecoveryServices"
    
  6. 可使用以下命令验证提供程序是否已成功注册:You can verify that the Providers registered successfully, using the following commands:

    Get-AzResourceProvider -ProviderNamespace "Microsoft.RecoveryServices"
    

    在命令输出中,RegistrationState 应当会变为 RegisteredIn the command output, the RegistrationState should change to Registered. 如果未按此更改,只需再次运行 Register-AzResourceProvider cmdlet 即可。If not, just run the Register-AzResourceProvider cmdlet again.

创建恢复服务保管库Create a Recovery Services vault

以下步骤引导用户创建恢复服务保管库。The following steps lead you through creating a Recovery Services vault. 恢复服务保管库不同于备份保管库。A Recovery Services vault is different than a Backup vault.

  1. 恢复服务保管库是一种 Resource Manager 资源,因此需要将它放在资源组中。The Recovery Services vault is a Resource Manager resource, so you need to place it within a resource group. 可以使用现有的资源组,也可以使用 New-AzResourceGroup cmdlet 创建资源组。You can use an existing resource group, or create a resource group with the New-AzResourceGroup cmdlet. 创建资源组时,请指定资源组的名称和位置。When creating a resource group, specify the name and location for the resource group.

    New-AzResourceGroup -Name "test-rg" -Location "China North"
    
  2. 使用 New-AzRecoveryServicesVault cmdlet 创建恢复服务保管库。Use the New-AzRecoveryServicesVault cmdlet to create the Recovery Services vault. 确保为保管库指定的位置与用于资源组的位置是相同的。Be sure to specify the same location for the vault as was used for the resource group.

    New-AzRecoveryServicesVault -Name "testvault" -ResourceGroupName "test-rg" -Location "China North"
    
  3. 指定要使用的存储冗余类型;可以使用本地冗余存储 (LRS)异地冗余存储 (GRS)Specify the type of storage redundancy to use; you can use Locally Redundant Storage (LRS) or Geo-redundant Storage (GRS). 以下示例显示,testvault 的 -BackupStorageRedundancy 选项设置为 GeoRedundant。The following example shows the -BackupStorageRedundancy option for testvault is set to GeoRedundant.

    $vault1 = Get-AzRecoveryServicesVault -Name "testvault"
    Set-AzRecoveryServicesBackupProperty  -Vault $vault1 -BackupStorageRedundancy GeoRedundant
    

    提示

    许多 Azure 备份 cmdlet 要求使用恢复服务保管库对象作为输入。Many Azure Backup cmdlets require the Recovery Services vault object as an input. 因此,在变量中存储备份恢复服务保管库对象可提供方便。For this reason, it is convenient to store the Backup Recovery Services vault object in a variable.

在订阅中查看保管库View the vaults in a subscription

若要查看订阅中的所有保管库,请使用 Get-AzRecoveryServicesVaultTo view all vaults in the subscription, use Get-AzRecoveryServicesVault:

Get-AzRecoveryServicesVault

输出类似于以下示例,请注意,提供了关联的 ResourceGroupName 和 Location。The output is similar to the following example, notice the associated ResourceGroupName and Location are provided.

Name              : Contoso-vault
ID                : /subscriptions/1234
Type              : Microsoft.RecoveryServices/vaults
Location          : ChinaNorth
ResourceGroupName : Contoso-docs-rg
SubscriptionId    : 1234-567f-8910-abc
Properties        : Microsoft.Azure.Commands.RecoveryServices.ARSVaultProperties

备份 Azure VMBack up Azure VMs

使用恢复服务保管库保护虚拟机。Use a Recovery Services vault to protect your virtual machines. 应用保护前,请先设置保管库上下文(保管库中受保护的数据类型)并验证保护策略。Before you apply the protection, set the vault context (the type of data protected in the vault), and verify the protection policy. 保护策略是指备份作业运行时以及每个备份快照的保留时长的计划。The protection policy is the schedule when the backup jobs run, and how long each backup snapshot is retained.

设置保管库上下文Set vault context

在 VM 上启用保护之前,请使用 Set-AzRecoveryServicesVaultContext 来设置保管库上下文。Before enabling protection on a VM, use Set-AzRecoveryServicesVaultContext to set the vault context. 设置保管库上下文后,它将应用于所有后续 cmdlet。Once the vault context is set, it applies to all subsequent cmdlets. 以下示例为保管库 testvault 设置保管库上下文。The following example sets the vault context for the vault, testvault.

Get-AzRecoveryServicesVault -Name "testvault" -ResourceGroupName "Contoso-docs-rg" | Set-AzRecoveryServicesVaultContext

提取保管库 IDFetch the vault ID

我们已计划根据 Azure PowerShell 指导原则弃用保管库上下文设置。We plan on deprecating the vault context setting in accordance with Azure PowerShell guidelines. 可以改为存储或提取保管库 ID,并将其传递给相关命令。Instead, you can store or fetch the vault ID, and pass it to relevant commands. 因此,如果你尚未设置保管库上下文或想要指定为某个保管库运行的命令,请将保管库 ID 作为“-vaultID”传递给所有相关命令,如下所示:So, if you haven't set the vault context or want to specify the command to run for a certain vault, pass the vault ID as "-vaultID" to all relevant command, as follows:

$targetVault = Get-AzRecoveryServicesVault -ResourceGroupName "Contoso-docs-rg" -Name "testvault"
$targetVault.ID

Or

$targetVaultID = Get-AzRecoveryServicesVault -ResourceGroupName "Contoso-docs-rg" -Name "testvault" | select -ExpandProperty ID

修改存储复制设置Modifying storage replication settings

使用 Set-AzRecoveryServicesBackupProperty 命令,将保管库的存储复制配置设置为 LRS/GRSUse Set-AzRecoveryServicesBackupProperty command to set the Storage replication configuration of the vault to LRS/GRS

Set-AzRecoveryServicesBackupProperty -Vault $targetVault -BackupStorageRedundancy GeoRedundant/LocallyRedundant

备注

只有在没有受保管库保护的备份项的情况下,才能修改存储冗余性。Storage Redundancy can be modified only if there are no backup items protected to the vault.

创建保护策略Create a protection policy

在创建恢复服务保管库时,它附带了默认的保护和保留策略。When you create a Recovery Services vault, it comes with default protection and retention policies. 默认保护策略在每天的指定时间触发备份作业。The default protection policy triggers a backup job each day at a specified time. 默认保留策略将每日恢复点保留 30 天。The default retention policy retains the daily recovery point for 30 days. 可以使用默认策略快速保护 VM,以后再使用不同的详细信息编辑该策略。You can use the default policy to quickly protect your VM and edit the policy later with different details.

若要查看保管库中可用的保护策略,请使用 Get-AzRecoveryServicesBackupProtectionPolicyUse Get-AzRecoveryServicesBackupProtectionPolicy to view the protection policies available in the vault. 可以使用此 cmdlet 获取特定策略,或者查看与某个工作负荷类型关联的策略。You can use this cmdlet to get a specific policy, or to view the policies associated with a workload type. 以下示例获取适用于工作负荷类型 AzureVM 的策略。The following example gets policies for workload type, AzureVM.

Get-AzRecoveryServicesBackupProtectionPolicy -WorkloadType "AzureVM" -VaultId $targetVault.ID

输出类似于以下示例:The output is similar to the following example:

Name                 WorkloadType       BackupManagementType BackupTime                DaysOfWeek
----                 ------------       -------------------- ----------                ----------
DefaultPolicy        AzureVM            AzureVM              4/14/2016 5:00:00 PM

备注

PowerShell 中 BackupTime 字段的时区是 UTC。The timezone of the BackupTime field in PowerShell is UTC. 但是,在 Azure 门户中显示备份时间时,时间根据本地时区调整。However, when the backup time is shown in the Azure portal, the time is adjusted to your local timezone.

一个备份保护策略至少与一个保留策略相关联。A backup protection policy is associated with at least one retention policy. 保留策略定义了在将恢复点删除之前将其保留多长时间。A retention policy defines how long a recovery point is kept before it is deleted.

默认情况下,会在“计划策略对象”中定义开始时间。By default, a start time is defined in the Schedule Policy Object. 请使用以下示例将开始时间更改为所需的开始时间。Use the following example to change the start time to the desired start time. 所需的开始时间也应采用 UTC 格式。The desired start time should be in UTC as well. 以下示例假设在进行每日备份时,所需的开始时间为 UTC 时间凌晨 1:00。The below example assumes the desired start time is 01:00 AM UTC for daily backups.

$schPol = Get-AzRecoveryServicesBackupSchedulePolicyObject -WorkloadType "AzureVM"
$UtcTime = Get-Date -Date "2019-03-20 01:00:00Z"
$UtcTime = $UtcTime.ToUniversalTime()
$schpol.ScheduleRunTimes[0] = $UtcTime

重要

只需以 30 分钟的倍数提供开始时间。You need to provide the start time in 30 minute multiples only. 在上面的示例中,开始时间只能是“01:00:00”或“02:30:00”。In the above example, it can be only "01:00:00" or "02:30:00". 开始时间不能为“01:15:00”The start time cannot be "01:15:00"

以下示例将计划策略和保留策略存储在变量中。The following example stores the schedule policy and the retention policy in variables. 此示例使用这些变量来定义在创建保护策略 NewPolicy 时要使用的参数。The example uses those variables to define the parameters when creating a protection policy, NewPolicy.

$retPol = Get-AzRecoveryServicesBackupRetentionPolicyObject -WorkloadType "AzureVM"
New-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -WorkloadType "AzureVM" -RetentionPolicy $retPol -SchedulePolicy $schPol -VaultId $targetVault.ID

输出类似于以下示例:The output is similar to the following example:

Name                 WorkloadType       BackupManagementType BackupTime                DaysOfWeek
----                 ------------       -------------------- ----------                ----------
NewPolicy           AzureVM            AzureVM              4/24/2016 1:30:00 AM

启用保护Enable protection

在定义保护策略后,还必须为相应的项启用该策略。Once you've defined the protection policy, you still must enable the policy for an item. 请使用 Enable-AzRecoveryServicesBackupProtection 来启用保护。Use Enable-AzRecoveryServicesBackupProtection to enable protection. 启用保护需要两个对象 - 项和策略。Enabling protection requires two objects - the item and the policy. 将策略与保管库关联之后,将在策略计划中定义的时间触发备份工作流。Once the policy has been associated with the vault, the backup workflow is triggered at the time defined in the policy schedule.

重要

使用 PS 一次为多个 VM 启用备份时,请确保单个策略关联的 VM 不超过 100 个。While using PS to enable backup for multiple VMs at once, ensure that a single policy doesn't have more than 100 VMs associated with it. 这是建议的最佳做法This is a recommended best practice. 目前,如果有超过 100 个 VM,PS 客户端不会显式阻止,但计划在将来添加检查。Currently, the PS client doesn't explicitly block if there are more than 100 VMs but the check is planned to be added in the future.

以下示例使用策略 NewPolicy 为项 V2VM 启用保护。The following examples enable protection for the item, V2VM, using the policy, NewPolicy. 根据 VM 是否已加密以及采用了何种加密类型,示例将有所不同。The examples differ based on whether the VM is encrypted, and what type of encryption.

非加密资源管理器 VM 上启用保护:To enable the protection on non-encrypted Resource Manager VMs:

$pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -VaultId $targetVault.ID
Enable-AzRecoveryServicesBackupProtection -Policy $pol -Name "V2VM" -ResourceGroupName "RGName1" -VaultId $targetVault.ID

若要在加密 VM(使用 BEK 和 KEK 加密)上启用保护,必须向 Azure 备份服务授予权限来读取密钥保管库中的密钥和机密。To enable the protection on encrypted VMs (encrypted using BEK and KEK), you must give the Azure Backup service permission to read keys and secrets from the key vault.

Set-AzKeyVaultAccessPolicy -VaultName "KeyVaultName" -ResourceGroupName "RGNameOfKeyVault" -PermissionsToKeys backup,get,list -PermissionsToSecrets get,list -ServicePrincipalName 262044b1-e2ce-469f-a196-69ab7ada62d3
$pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -VaultId $targetVault.ID
Enable-AzRecoveryServicesBackupProtection -Policy $pol -Name "V2VM" -ResourceGroupName "RGName1" -VaultId $targetVault.ID

若要在加密 VM(仅使用 BEK 加密的) 上启用保护,必须向 Azure 备份服务授予权限来读取密钥保管库中的机密。To enable the protection on encrypted VMs (encrypted using BEK only), you must give the Azure Backup service permission to read secrets from the key vault.

Set-AzKeyVaultAccessPolicy -VaultName "KeyVaultName" -ResourceGroupName "RGNameOfKeyVault" -PermissionsToSecrets backup,get,list -ServicePrincipalName 262044b1-e2ce-469f-a196-69ab7ada62d3
$pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -VaultId $targetVault.ID
Enable-AzRecoveryServicesBackupProtection -Policy $pol -Name "V2VM" -ResourceGroupName "RGName1" -VaultId $targetVault.ID

监视备份作业Monitoring a backup job

可以在不使用 Azure 门户的情况下监视长时间运行的操作,例如备份作业。You can monitor long-running operations, such as backup jobs, without using the Azure portal. 若要获取正在进行的作业的状态,请使用 Get-AzRecoveryservicesBackupJob cmdlet。To get the status of an in-progress job, use the Get-AzRecoveryservicesBackupJob cmdlet. 此 cmdlet 获取特定保管库的备份作业,并且该保管库是在保管库上下文中指定的。This cmdlet gets the backup jobs for a specific vault, and that vault is specified in the vault context. 以下示例将正在进行的作业的状态获取为数组,并将状态存储在 $joblist 变量中。The following example gets the status of an in-progress job as an array, and stores the status in the $joblist variable.

$joblist = Get-AzRecoveryservicesBackupJob -Status "InProgress" -VaultId $targetVault.ID
$joblist[0]

输出类似于以下示例:The output is similar to the following example:

WorkloadName     Operation            Status               StartTime                 EndTime                   JobID
------------     ---------            ------               ---------                 -------                   ----------
V2VM             Backup               InProgress            4/23/2016                5:00:30 PM                cf4b3ef5-2fac-4c8e-a215-d2eba4124f27

与其使用额外的不必要的代码来轮询这些作业的完成情况,不如使用 Wait-AzRecoveryServicesBackupJob cmdlet。Instead of polling these jobs for completion - which is unnecessary additional code - use the Wait-AzRecoveryServicesBackupJob cmdlet. 该 cmdlet 暂停操作的执行,直到作业完成或达到了指定的超时值。This cmdlet pauses the execution until either the job completes or the specified timeout value is reached.

Wait-AzRecoveryServicesBackupJob -Job $joblist[0] -Timeout 43200 -VaultId $targetVault.ID

管理 Azure VM 备份Manage Azure VM backups

修改保护策略Modify a protection policy

若要修改保护策略,请使用 Set-AzRecoveryServicesBackupProtectionPolicy 修改 SchedulePolicy 或 RetentionPolicy 对象。To modify the protection policy, use Set-AzRecoveryServicesBackupProtectionPolicy to modify the SchedulePolicy or RetentionPolicy objects.

修改计划时间Modifying scheduled time

创建保护策略时,默认情况下会为其分配开始时间。When you create a protection policy, it is assigned a start-time by default. 下面的示例演示如何修改保护策略的开始时间。The following examples show how to modify the start time of a protection policy.

$SchPol = Get-AzRecoveryServicesBackupSchedulePolicyObject -WorkloadType "AzureVM"
$UtcTime = Get-Date -Date "2019-03-20 01:00:00Z" (This is the time that the customer wants to start the backup)
$UtcTime = $UtcTime.ToUniversalTime()
$SchPol.ScheduleRunTimes[0] = $UtcTime
$pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -VaultId $targetVault.ID
Set-AzRecoveryServicesBackupProtectionPolicy -Policy $pol  -SchedulePolicy $SchPol -VaultId $targetVault.ID

修改保留期Modifying retention

以下示例将恢复点保留期更改为 365 天。The following example changes the recovery point retention to 365 days.

$retPol = Get-AzRecoveryServicesBackupRetentionPolicyObject -WorkloadType "AzureVM"
$retPol.DailySchedule.DurationCountInDays = 365
$pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name "NewPolicy" -VaultId $targetVault.ID
Set-AzRecoveryServicesBackupProtectionPolicy -Policy $pol  -RetentionPolicy $RetPol -VaultId $targetVault.ID

配置即时还原快照保留期Configuring Instant restore snapshot retention

备注

从 Az PS 版本 1.6.0 开始,用户可以使用 Powershell 在策略中更新即时还原快照保留期From Az PS version 1.6.0 onwards, one can update the instant restore snapshot retention period in policy using Powershell

$bkpPol = Get-AzRecoveryServicesBackupProtectionPolicy -WorkloadType "AzureVM" -VaultId $targetVault.ID
$bkpPol.SnapshotRetentionInDays=7
Set-AzRecoveryServicesBackupProtectionPolicy -policy $bkpPol -VaultId $targetVault.ID

默认值为 2,用户可以将值设置为 1 到 5。The default value will be 2, user can set the value with a min of 1 and max of 5. 每周备份策略的保留期设置为 5,不能更改。For weekly backup policies, the period is set to 5 and cannot be changed.

在快照保留期间创建 Azure 备份资源组Creating Azure Backup resource group during snapshot retention

备注

从 Azure PS 3.7.0 版开始,用户可以创建和编辑为存储即时快照而创建的资源组。From Azure PS version 3.7.0 onwards, one can create and edit the resource group created for storing instant snapshots.

若要详细了解资源组创建规则和其他相关详细信息,请参阅适用于虚拟机的 Azure 备份资源组文档。To understand more about resource group creation rules and other relevant details, refer to the Azure Backup resource group for Virtual Machines documentation.

$bkpPol = Get-AzureRmRecoveryServicesBackupProtectionPolicy -name "DefaultPolicyForVMs"
$bkpPol.AzureBackupRGName="Contosto_"
$bkpPol.AzureBackupRGNameSuffix="ForVMs"
Set-AzureRmRecoveryServicesBackupProtectionPolicy -policy $bkpPol

触发备份Trigger a backup

请使用 Backup-AzRecoveryServicesBackupItem 来触发备份作业。Use Backup-AzRecoveryServicesBackupItem to trigger a backup job. 如果它是初始备份,则是一个完整备份。If it's the initial backup, it is a full backup. 后续备份将创建增量副本。Subsequent backups take an incremental copy. 以下示例将 VM 备份保留 60 天。The following example takes a VM backup to be retained for 60 days.

$namedContainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -Status "Registered" -FriendlyName "V2VM" -VaultId $targetVault.ID
$item = Get-AzRecoveryServicesBackupItem -Container $namedContainer -WorkloadType "AzureVM" -VaultId $targetVault.ID
$endDate = (Get-Date).AddDays(60).ToUniversalTime()
$job = Backup-AzRecoveryServicesBackupItem -Item $item -VaultId $targetVault.ID -ExpiryDateTimeUTC $endDate

输出类似于以下示例:The output is similar to the following example:

WorkloadName     Operation            Status               StartTime                 EndTime                   JobID
------------     ---------            ------               ---------                 -------                   ----------
V2VM              Backup              InProgress          4/23/2016                  5:00:30 PM                cf4b3ef5-2fac-4c8e-a215-d2eba4124f27

备注

PowerShell 中 StartTime 和 EndTime 字段的时区是 UTC。The timezone of the StartTime and EndTime fields in PowerShell is UTC. 但是,在 Azure 门户中显示时间时,时间根据本地时区调整。However, when the time is shown in the Azure portal, the time is adjusted to your local timezone.

更改备份项的策略Change policy for backup items

用户可以修改现有策略,也可以将备份项的策略从 Policy1 更改为 Policy2。User can either modify existing policy or change the policy of the backed-up item from Policy1 to Policy2. 若要切换备份项的策略,请提取相关策略并备份项,并使用 Enable-AzRecoveryServices 命令以备份项作为参数。To switch policies for a backed-up item, fetch the relevant policy and back up item and use the Enable-AzRecoveryServices command with backup item as the parameter.

$TargetPol1 = Get-AzRecoveryServicesBackupProtectionPolicy -Name <PolicyName> -VaultId $targetVault.ID
$anotherBkpItem = Get-AzRecoveryServicesBackupItem -WorkloadType AzureVM -BackupManagementType AzureVM -Name "<BackupItemName>" -VaultId $targetVault.ID
Enable-AzRecoveryServicesBackupProtection -Item $anotherBkpItem -Policy $TargetPol1 -VaultId $targetVault.ID

该命令将一直等到配置备份完成并返回以下输出。The command waits until the configure backup is completed and returns the following output.

WorkloadName     Operation            Status               StartTime                 EndTime                   JobID
------------     ---------            ------               ---------                 -------                   -----
TestVM           ConfigureBackup      Completed            3/18/2019 8:00:21 PM      3/18/2019 8:02:16 PM      654e8aa2-4096-402b-b5a9-e5e71a496c4e

停止保护Stop protection

保留数据Retain data

如果用户想要停止保护,他们可以使用 Disable-AzRecoveryServicesBackupProtection PS cmdlet。If user wishes to stop protection, they can use the Disable-AzRecoveryServicesBackupProtection PS cmdlet. 此命令将停止计划的备份,但到目前为止备份的数据将永远保留。This will stop the scheduled backups but the data backed up until now is retained forever.

$bkpItem = Get-AzRecoveryServicesBackupItem -BackupManagementType AzureVM -WorkloadType AzureVM -Name "<backup item name>" -VaultId $targetVault.ID
Disable-AzRecoveryServicesBackupProtection -Item $bkpItem -VaultId $targetVault.ID

删除备份数据Delete backup data

若要完全删除保管库中存储的备份数据,只需将“-RemoveRecoveryPoints”标志/开关添加到“disable”保护命令In order to completely remove the stored backup data in the vault, just add '-RemoveRecoveryPoints' flag/switch to the 'disable' protection command.

Disable-AzRecoveryServicesBackupProtection -Item $bkpItem -VaultId $targetVault.ID -RemoveRecoveryPoints

还原 Azure VMRestore an Azure VM

使用 Azure 门户还原 VM 与使用 PowerShell 还原 VM 存在重要区别。There is an important difference between the restoring a VM using the Azure portal and restoring a VM using PowerShell. 如果使用 PowerShell,从恢复点创建磁盘和配置信息即可完成还原操作。With PowerShell, the restore operation is complete once the disks and configuration information from the recovery point are created. 还原操作不会创建虚拟机。The restore operation doesn't create the virtual machine. 若要通过磁盘创建虚拟机,请参阅通过存储磁盘创建 VM 部分。To create a virtual machine from disk, see the section, Create the VM from restored disks. 如果不希望还原整个 VM,但希望从 Azure VM 备份还原或恢复几个文件,请参阅文件恢复部分If you don't want to restore the entire VM, but want to restore or recover a few files from an Azure VM backup, refer to the file recovery section.

提示

还原操作不会创建虚拟机。The restore operation does not create the virtual machine.

下图显示了从 RecoveryServicesVault 到 BackupRecoveryPoint 的对象层次结构。The following graphic shows the object hierarchy from the RecoveryServicesVault down to the BackupRecoveryPoint.

显示 BackupContainer 的恢复服务对象层次结构

若要还原备份数据,请确定已备份项目以及保留了时间点数据的恢复点。To restore backup data, identify the backed-up item and the recovery point that holds the point-in-time data. 请使用 Restore-AzRecoveryServicesBackupItem 将数据从保管库还原到帐户。Use Restore-AzRecoveryServicesBackupItem to restore data from the vault to your account.

还原 Azure VM 的基本步骤是:The basic steps to restore an Azure VM are:

  • 选择 VM。Select the VM.
  • 选择恢复点。Choose a recovery point.
  • 还原磁盘。Restore the disks.
  • 基于还原后的磁盘创建 VM。Create the VM from stored disks.

选择 VMSelect the VM

若要获取用于标识正确备份项的 PowerShell 对象,请从保管库中的容器开始,按对象层次结构进行操作。To get the PowerShell object that identifies the right backup item, start from the container in the vault, and work your way down the object hierarchy. 若要选择代表 VM 的容器,请使用 Get-AzRecoveryServicesBackupContainer cmdlet,然后通过管道将其传递给 Get-AzRecoveryServicesBackupItem cmdlet。To select the container that represents the VM, use the Get-AzRecoveryServicesBackupContainer cmdlet and pipe that to the Get-AzRecoveryServicesBackupItem cmdlet.

$namedContainer = Get-AzRecoveryServicesBackupContainer  -ContainerType "AzureVM" -Status "Registered" -FriendlyName "V2VM" -VaultId $targetVault.ID
$backupitem = Get-AzRecoveryServicesBackupItem -Container $namedContainer  -WorkloadType "AzureVM" -VaultId $targetVault.ID

选择恢复点Choose a recovery point

使用 Get-AzRecoveryServicesBackupRecoveryPoint cmdlet 列出备份项的所有恢复点。Use the Get-AzRecoveryServicesBackupRecoveryPoint cmdlet to list all recovery points for the backup item. 然后选择要还原的恢复点。Then choose the recovery point to restore. 如果不确定要使用的恢复点,最好选择列表中最新的 RecoveryPointType = AppConsistent 恢复点。If you are unsure which recovery point to use, it is a good practice to choose the most recent RecoveryPointType = AppConsistent point in the list.

在以下脚本中,变量 $rp 是一个数组,其中包含所选备份项在过去七天的恢复点。In the following script, the variable, $rp, is an array of recovery points for the selected backup item, from the past seven days. 该数组按时间进行反向排序,以最新的恢复点作为索引 0。The array is sorted in reverse order of time with the latest recovery point at index 0. 使用标准 PowerShell 数组索引选取恢复点。Use standard PowerShell array indexing to pick the recovery point. 在示例中,$rp[0] 选择最新的恢复点。In the example, $rp[0] selects the latest recovery point.

$startDate = (Get-Date).AddDays(-7)
$endDate = Get-Date
$rp = Get-AzRecoveryServicesBackupRecoveryPoint -Item $backupitem -StartDate $startdate.ToUniversalTime() -EndDate $enddate.ToUniversalTime() -VaultId $targetVault.ID
$rp[0]

输出类似于以下示例:The output is similar to the following example:

RecoveryPointAdditionalInfo :
SourceVMStorageType         : NormalStorage
Name                        : 15260861925810
ItemName                    : VM;iaasvmcontainer;RGName1;V2VM
RecoveryPointId             : /subscriptions/XX/resourceGroups/ RGName1/providers/Microsoft.RecoveryServices/vaults/testvault/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainer;RGName1;V2VM/protectedItems/VM;iaasvmcontainer; RGName1;V2VM/recoveryPoints/15260861925810
RecoveryPointType           : AppConsistent
RecoveryPointTime           : 4/23/2016 5:02:04 PM
WorkloadType                : AzureVM
ContainerName               : IaasVMContainer;iaasvmcontainer; RGName1;V2VM
ContainerType               : AzureVM
BackupManagementType        : AzureVM

还原磁盘Restore the disks

请使用 Restore-AzRecoveryServicesBackupItem cmdlet 将备份项的数据和配置还原到某个恢复点。Use the Restore-AzRecoveryServicesBackupItem cmdlet to restore a backup item's data and configuration to a recovery point. 确定某个恢复点后,即可使用它作为 -RecoveryPoint 参数的值。Once you identify a recovery point, use it as the value for the -RecoveryPoint parameter. 在上面的示例中, $rp[0] 是要使用的恢复点。In the above sample, $rp[0] was the recovery point to use. 在下面的示例代码中, $rp[0] 是还原磁盘时要使用的恢复点。In the following sample code, $rp[0] is the recovery point to use for restoring the disk.

还原磁盘和配置信息:To restore the disks and configuration information:

$restorejob = Restore-AzRecoveryServicesBackupItem -RecoveryPoint $rp[0] -StorageAccountName "DestAccount" -StorageAccountResourceGroupName "DestRG" -VaultId $targetVault.ID
$restorejob

还原托管磁盘Restore managed disks

备注

如果备份的 VM 具有托管磁盘,并且你想要将其还原为托管磁盘,我们从 Azure PowerShell RM 模块 v 6.7.0 引入了相关功能。If the backed VM has managed disks and you want to restore them as managed disks, we have introduced the capability from Azure PowerShell RM module v 6.7.0. 更高版本onwards

提供了附加参数 TargetResourceGroupName 来指定托管磁盘要还原到的 RG。Provide an additional parameter TargetResourceGroupName to specify the RG to which managed disks will be restored.

重要

强烈建议使用 TargetResourceGroupName 参数来还原托管磁盘,因为它可以显著提高性能。It is strongly recommended to use the TargetResourceGroupName parameter for restoring managed disks since it results in significant performance improvements. 如果未指定此参数,则客户将无法从即时还原功能中受益,并且相比之下,还原操作的速度将更慢。If this parameter is not given, then customers cannot benefit from the instant restore functionality and the restore operation will be slower in comparison. 如果目的是将托管磁盘还原为非托管磁盘,则不要提供此参数,而应通过提供 -RestoreAsUnmanagedDisks 参数,使该目的明确。If the purpose is to restore managed disks as unmanaged disks, then do not provide this parameter and make the intention clear by providing the -RestoreAsUnmanagedDisks parameter. 从 Az PS 3.7.0 开始,可以使用 -RestoreAsUnmanagedDisks 参数。The -RestoreAsUnmanagedDisks parameter is available from Az PS 3.7.0 onwards. 在将来的版本中,必须提供其中任意一个参数,以获得正确的还原体验In future versions, it will be mandatory to provide either of these parameters for the right restore experience

$restorejob = Restore-AzRecoveryServicesBackupItem -RecoveryPoint $rp[0] -StorageAccountName "DestAccount" -StorageAccountResourceGroupName "DestRG" -TargetResourceGroupName "DestRGforManagedDisks" -VaultId $targetVault.ID

VMConfig.JSON 文件将还原到存储帐户,托管磁盘将还原到指定的目标 RG。The VMConfig.JSON file will be restored to the storage account and the managed disks will be restored to the specified target RG.

输出类似于以下示例:The output is similar to the following example:

WorkloadName     Operation          Status               StartTime                 EndTime            JobID
------------     ---------          ------               ---------                 -------          ----------
V2VM              Restore           InProgress           4/23/2016 5:00:30 PM                        cf4b3ef5-2fac-4c8e-a215-d2eba4124f27

请使用 Wait-AzRecoveryServicesBackupJob cmdlet 等待还原作业完成。Use the Wait-AzRecoveryServicesBackupJob cmdlet to wait for the Restore job to complete.

Wait-AzRecoveryServicesBackupJob -Job $restorejob -Timeout 43200

还原作业完成后,请使用 Get-AzRecoveryServicesBackupJobDetails cmdlet 获取还原操作的详细信息。Once the Restore job has completed, use the Get-AzRecoveryServicesBackupJobDetails cmdlet to get the details of the restore operation. JobDetails 属性提供重建 VM 所需的信息。The JobDetails property has the information needed to rebuild the VM.

$restorejob = Get-AzRecoveryServicesBackupJob -Job $restorejob -VaultId $targetVault.ID
$details = Get-AzRecoveryServicesBackupJobDetails -Job $restorejob -VaultId $targetVault.ID

还原磁盘以后,转到下一部分来了解如何创建 VM。Once you restore the disks, go to the next section to create the VM.

更换 Azure VM 中的磁盘Replace disks in Azure VM

若要更换磁盘和配置信息,请执行以下步骤:To replace the disks and configuration information, perform the below steps:

从还原的磁盘创建 VMCreate a VM from restored disks

还原磁盘以后,通过以下步骤从磁盘创建和配置虚拟机。After you restore the disks, use the following steps to create and configure the virtual machine from disk.

备注

  1. 需要 AzureAz 模块 3.0.0 或更高版本。AzureAz module 3.0.0 or higher is required.
  2. 若要使用已还原的磁盘创建加密 VM,则 Azure 角色必须有权执行 Microsoft.KeyVault/vaults/deploy/action 操作。To create encrypted VMs from restored disks, your Azure role must have permission to perform the action, Microsoft.KeyVault/vaults/deploy/action. 如果用户角色不具有此权限,请创建具有此操作的自定义角色。If your role does not have this permission, create a custom role with this action. 有关详细信息,请参阅 Custom Roles in Azure RBAC(Azure RBAC 中的自定义角色)。For more information, see Custom Roles in Azure RBAC.
  3. 还原磁盘后,你现在可以获取可以直接用来创建新 VM 的部署模板。After restoring disks, you can now get a deployment template which you can directly use to create a new VM. 没有更多不同的 PS cmdlet 可用来创建加密/未加密的托管/非托管 VM。No more different PS cmdlets to create managed/unmanaged VMs which are encrypted/unencrypted.

使用部署模板创建 VMCreate a VM using the deployment template

生成的作业详细信息提供了可以查询和部署的模板 URI。The resultant job details give the template URI that can be queried and deployed.

   $properties = $details.properties
   $storageAccountName = $properties["Target Storage Account Name"]
   $containerName = $properties["Config Blob Container Name"]
   $templateBlobURI = $properties["Template Blob Uri"]

模板不可直接进行访问,因为它位于客户的存储帐户和给定容器下。The template is not directly accessible since it is under a customer's storage account and the given container. 需要完整的 URL(连同临时 SAS 令牌)才能访问此模板。We need the complete URL (along with a temporary SAS token) to access this template.

  1. 首先从 templateBlobURI 中提取模板名称。First extract the template name from the templateBlobURI. 此格式如下所述。The format is mentioned below. 可以使用 Powershell 中的拆分操作从该 URL 提取最终模板名称。You can use the split operation in Powershell to extract the final template name from this URL.

    https://<storageAccountName.blob.core.chinacloudapi.cn>/<containerName>/<templateName>
    
  2. 然后,可以生成完整的 URL,如此处所述。Then the full URL can be generated as explained here.

    Set-AzCurrentStorageAccount -Name $storageAccountName -ResourceGroupName <StorageAccount RG name>
    $templateBlobFullURI = New-AzStorageBlobSASToken -Container $containerName -Blob <templateName> -Permission r -FullUri
    
  3. 部署模板来创建新的 VM,如此处所述。Deploy the template to create a new VM as explained here.

    New-AzResourceGroupDeployment -Name ExampleDeployment ResourceGroupName ExampleResourceGroup -TemplateUri $templateBlobFullURI -storageAccountType Standard_GRS
    

使用配置文件创建 VMCreate a VM using the config file

以下部分列出了使用“VMConfig”文件创建 VM 所需的步骤。The following section lists steps necessary to create a VM using "VMConfig" file.

备注

强烈建议使用上面详述的部署模板来创建 VM。It is highly recommended to use the deployment template detailed above to create a VM. 本部分(要点 1-6)不久将被弃用。This section (Points 1-6) will be deprecated soon.

  1. 查询已还原磁盘属性以获取作业详细信息。Query the restored disk properties for the job details.

    $properties = $details.properties
    $storageAccountName = $properties["Target Storage Account Name"]
    $containerName = $properties["Config Blob Container Name"]
    $configBlobName = $properties["Config Blob Name"]
    
  2. 设置 Azure 存储上下文和还原 JSON 配置文件。Set the Azure storage context and restore the JSON configuration file.

    Set-AzCurrentStorageAccount -Name $storageaccountname -ResourceGroupName "testvault"
    $destination_path = "C:\vmconfig.json"
    Get-AzStorageBlobContent -Container $containerName -Blob $configBlobName -Destination $destination_path
    $obj = ((Get-Content -Path $destination_path -Raw -Encoding Unicode)).TrimEnd([char]0x00) | ConvertFrom-Json
    
  3. 使用 JSON 配置文件来创建 VM 配置。Use the JSON configuration file to create the VM configuration.

    $vm = New-AzVMConfig -VMSize $obj.'properties.hardwareProfile'.vmSize -VMName "testrestore"
    
  4. 附加 OS 磁盘和数据磁盘。Attach the OS disk and data disks. 此步骤提供了各种托管和加密的 VM 配置的示例。This step provides examples for various managed and encrypted VM configurations. 请使用适合你的 VM 配置的示例。Use the example that suits your VM configuration.

    • 非托管且非加密 VM - 对于非托管的非加密 VM,请使用以下示例。Non-managed and non-encrypted VMs - Use the following sample for non-managed, non-encrypted VMs.
        Set-AzVMOSDisk -VM $vm -Name "osdisk" -VhdUri $obj.'properties.StorageProfile'.osDisk.vhd.Uri -CreateOption "Attach"
        $vm.StorageProfile.OsDisk.OsType = $obj.'properties.StorageProfile'.OsDisk.OsType
        foreach($dd in $obj.'properties.StorageProfile'.DataDisks)
        {
            $vm = Add-AzVMDataDisk -VM $vm -Name "datadisk1" -VhdUri $dd.vhd.Uri -DiskSizeInGB 127 -Lun $dd.Lun -CreateOption "Attach"
        }
    
    • 使用 Azure AD 的非托管加密 VM(仅限 BEK) - 对于使用 Azure AD 的非托管加密 VM(仅限使用 BEK 加密),需先将机密还原到 Key Vault,然后才能附加磁盘。Non-managed and encrypted VMs with Azure AD (BEK only) - For non-managed, encrypted VMs with Azure AD (encrypted using BEK only), you need to restore the secret to the key vault before you can attach disks. 有关详细信息,请参阅从 Azure 备份恢复点还原已加密的虚拟机For more information, see the Restore an encrypted virtual machine from an Azure Backup recovery point. 以下示例展示了如何为加密的 VM 附加 OS 和数据磁盘。The following sample shows how to attach OS and data disks for encrypted VMs. 设置 OS 磁盘时,请确保提及相关的 OS 类型。When setting the OS disk, make sure to mention the relevant OS type.
        $dekUrl = "https://ContosoKeyVault.vault.azure.cn:443/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
        $dekUrl = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
        Set-AzVMOSDisk -VM $vm -Name "osdisk" -VhdUri $obj.'properties.storageProfile'.osDisk.vhd.uri -DiskEncryptionKeyUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId -CreateOption "Attach" -Windows/Linux
        $vm.StorageProfile.OsDisk.OsType = $obj.'properties.storageProfile'.osDisk.osType
        foreach($dd in $obj.'properties.storageProfile'.dataDisks)
        {
        $vm = Add-AzVMDataDisk -VM $vm -Name "datadisk1" -VhdUri $dd.vhd.Uri -DiskSizeInGB 127 -Lun $dd.Lun -CreateOption "Attach"
        }
    
    • 使用 Azure AD 的非托管加密 VM(BEK 和 KEK) - 对于使用 Azure AD 的非托管加密 VM(使用 BEK 和 KEK 加密),需先将密钥和机密还原到 Key Vault,然后才能附加磁盘。Non-managed and encrypted VMs with Azure AD (BEK and KEK) - For non-managed, encrypted VMs with Azure AD (encrypted using BEK and KEK), restore the key and secret to the key vault before attaching the disks. 有关详细信息,请参阅从 Azure 备份恢复点还原已加密的虚拟机For more information, see Restore an encrypted virtual machine from an Azure Backup recovery point. 以下示例展示了如何为加密的 VM 附加 OS 和数据磁盘。The following sample shows how to attach OS and data disks for encrypted VMs.
        $dekUrl = "https://ContosoKeyVault.vault.azure.cn:443/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
        $kekUrl = "https://ContosoKeyVault.vault.azure.cn:443/keys/ContosoKey007/x9xxx00000x0000x9b9949999xx0x006"
        $keyVaultId = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
        Set-AzVMOSDisk -VM $vm -Name "osdisk" -VhdUri $obj.'properties.storageProfile'.osDisk.vhd.uri -DiskEncryptionKeyUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId -KeyEncryptionKeyUrl $kekUrl -KeyEncryptionKeyVaultId $keyVaultId -CreateOption "Attach" -Windows
        $vm.StorageProfile.OsDisk.OsType = $obj.'properties.storageProfile'.osDisk.osType
        foreach($dd in $obj.'properties.storageProfile'.dataDisks)
        {
        $vm = Add-AzVMDataDisk -VM $vm -Name "datadisk1" -VhdUri $dd.vhd.Uri -DiskSizeInGB 127 -Lun $dd.Lun -CreateOption "Attach"
        }
    
    • 不使用 Azure AD 的非托管加密 VM(仅限 BEK) - 对于不使用 Azure AD 的非托管加密 VM(仅限使用 BEK 加密),如果源 keyVault/机密不可用,请使用从 Azure 备份恢复点还原未加密的虚拟机中的过程,将机密还原到 Key Vault。Non-managed and encrypted VMs without Azure AD (BEK only) - For non-managed, encrypted VMs without Azure AD (encrypted using BEK only), if source keyVault/secret are not available restore the secrets to key vault using the procedure in Restore an non-encrypted virtual machine from an Azure Backup recovery point. 然后执行以下脚本,在已还原的 OS Blob 上设置加密详细信息(对于数据 Blob,不需要执行此步骤)。Then execute the following scripts to set encryption details on the restored OS blob (this step is not required for data blob). 可从已还原的 keyVault 提取 $dekurl。The $dekurl can be fetched from the restored keyVault.

    仅当源 keyVault/机密不可用时,才需要执行以下脚本。The below script needs to be executed only when the source keyVault/secret is not available.

        $dekUrl = "https://ContosoKeyVault.vault.azure.cn/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
        $keyVaultId = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
        $encSetting = "{""encryptionEnabled"":true,""encryptionSettings"":[{""diskEncryptionKey"":{""sourceVault"":{""id"":""$keyVaultId""},""secretUrl"":""$dekUrl""}}]}"
        $osBlobName = $obj.'properties.StorageProfile'.osDisk.name + ".vhd"
        $osBlob = Get-AzStorageBlob -Container $containerName -Blob $osBlobName
        $osBlob.ICloudBlob.Metadata["DiskEncryptionSettings"] = $encSetting
        $osBlob.ICloudBlob.SetMetadata()
    

    机密可用并且同时在 OS Blob 上设置加密详细信息之后,使用下面提供的脚本附加磁盘。After the secrets are available and the encryption details are also set on the OS Blob, attach the disks using the script given below.

    如果源 keyVault/机密已经可用,则不需要执行上述脚本。If the source keyVault/secrets are available already, then the above script need not be executed.

        Set-AzVMOSDisk -VM $vm -Name "osdisk" -VhdUri $obj.'properties.StorageProfile'.osDisk.vhd.Uri -CreateOption "Attach"
        $vm.StorageProfile.OsDisk.OsType = $obj.'properties.StorageProfile'.OsDisk.OsType
        foreach($dd in $obj.'properties.StorageProfile'.DataDisks)
        {
        $vm = Add-AzVMDataDisk -VM $vm -Name "datadisk1" -VhdUri $dd.vhd.Uri -DiskSizeInGB 127 -Lun $dd.Lun -CreateOption "Attach"
        }
    
    • 不使用 Azure AD 的非托管加密 VM(BEK 和 KEK) - 对于不使用 Azure AD 的非托管加密 VM(使用 BEK 和 KEK 加密),如果源 keyVault/密钥/机密不可用,请使用从 Azure 备份恢复点还原未加密的虚拟机中的过程,将密钥和机密还原到 Key Vault。Non-managed and encrypted VMs without Azure AD (BEK and KEK) - For non-managed, encrypted VMs without Azure AD (encrypted using BEK & KEK), if source keyVault/key/secret are not available restore the key and secrets to key vault using the procedure in Restore an non-encrypted virtual machine from an Azure Backup recovery point. 然后执行以下脚本,在已还原的 OS Blob 上设置加密详细信息(对于数据 Blob,不需要执行此步骤)。Then execute the following scripts to set encryption details on the restored OS blob (this step is not required for data blob). 可从已还原的 keyVault 提取 $dekurl 和 $kekurl。The $dekurl and $kekurl can be fetched from the restored keyVault.

    仅当源 keyVault/密钥/机密不可用时,才需要执行以下脚本。The below script needs to be executed only when the source keyVault/key/secret is not available.

        $dekUrl = "https://ContosoKeyVault.vault.azure.cn/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
        $kekUrl = "https://ContosoKeyVault.vault.azure.cn/keys/ContosoKey007/x9xxx00000x0000x9b9949999xx0x006"
        $keyVaultId = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
        $encSetting = "{""encryptionEnabled"":true,""encryptionSettings"":[{""diskEncryptionKey"":{""sourceVault"":{""id"":""$keyVaultId""},""secretUrl"":""$dekUrl""},""keyEncryptionKey"":{""sourceVault"":{""id"":""$keyVaultId""},""keyUrl"":""$kekUrl""}}]}"
        $osBlobName = $obj.'properties.StorageProfile'.osDisk.name + ".vhd"
        $osBlob = Get-AzStorageBlob -Container $containerName -Blob $osBlobName
        $osBlob.ICloudBlob.Metadata["DiskEncryptionSettings"] = $encSetting
        $osBlob.ICloudBlob.SetMetadata()
    

    密钥/机密可用并且在 OS Blob 上设置加密详细信息之后,使用下面提供的脚本附加磁盘。After the key/secrets are available and the encryption details are set on the OS Blob, attach the disks using the script given below.

    如果源 keyVault/密钥/机密可用,则不需要执行上述脚本。If the source keyVault/key/secrets are available, then the above script need not be executed.

        Set-AzVMOSDisk -VM $vm -Name "osdisk" -VhdUri $obj.'properties.StorageProfile'.osDisk.vhd.Uri -CreateOption "Attach"
        $vm.StorageProfile.OsDisk.OsType = $obj.'properties.StorageProfile'.OsDisk.OsType
        foreach($dd in $obj.'properties.StorageProfile'.DataDisks)
        {
        $vm = Add-AzVMDataDisk -VM $vm -Name "datadisk1" -VhdUri $dd.vhd.Uri -DiskSizeInGB 127 -Lun $dd.Lun -CreateOption "Attach"
        }
    
    • 托管的非加密 VM -对于托管的非加密 VM,将附加还原的托管磁盘。Managed and non-encrypted VMs - For managed non-encrypted VMs, attach the restored managed disks. 有关深入信息,请参阅使用 PowerShell 将数据磁盘附加到 Windows VMFor in-depth information, see Attach a data disk to a Windows VM using PowerShell.

    • 使用 Azure AD 的托管加密 VM(仅限 BEK) - 对于使用 Azure AD 的托管加密 VM(仅限使用 BEK 加密),请附加已还原的托管磁盘。Managed and encrypted VMs with Azure AD (BEK only) - For managed encrypted VMs with Azure AD (encrypted using BEK only), attach the restored managed disks. 有关深入信息,请参阅使用 PowerShell 将数据磁盘附加到 Windows VMFor in-depth information, see Attach a data disk to a Windows VM using PowerShell.

    • 使用 Azure AD 的托管加密 VM(BEK 和 KEK) - 对于使用 Azure AD 的托管加密 VM(使用 BEK 和 KEK 加密),请附加已还原的托管磁盘。Managed and encrypted VMs with Azure AD (BEK and KEK) - For managed encrypted VMs with Azure AD (encrypted using BEK and KEK), attach the restored managed disks. 有关深入信息,请参阅使用 PowerShell 将数据磁盘附加到 Windows VMFor in-depth information, see Attach a data disk to a Windows VM using PowerShell.

    • 不使用 Azure AD 的托管加密 VM(仅限 BEK) - 对于不使用 Azure AD 的托管加密 VM(仅限使用 BEK 加密),如果源 keyVault/机密不可用,请使用从 Azure 备份恢复点还原未加密的虚拟机中的过程,将机密还原到密钥保管库。Managed and encrypted VMs without Azure AD (BEK only) -For managed, encrypted VMs without Azure AD (encrypted using BEK only), if source keyVault/secret are not available restore the secrets to key vault using the procedure in Restore an non-encrypted virtual machine from an Azure Backup recovery point. 然后执行以下脚本,在已还原的 OS 磁盘上设置加密详细信息(对于数据磁盘,不需要执行此步骤)。Then execute the following scripts to set encryption details on the restored OS disk (this step is not required for data disk). 可从已还原的 keyVault 提取 $dekurl。The $dekurl can be fetched from the restored keyVault.

    仅当源 keyVault/机密不可用时,才需要执行以下脚本。The below script needs to be executed only when the source keyVault/secret is not available.

    $dekUrl = "https://ContosoKeyVault.vault.azure.cn/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
    $keyVaultId = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
    $diskupdateconfig = New-AzDiskUpdateConfig -EncryptionSettingsEnabled $true
    $encryptionSettingsElement = New-Object Microsoft.Azure.Management.Compute.Models.EncryptionSettingsElement
    $encryptionSettingsElement.DiskEncryptionKey = New-Object Microsoft.Azure.Management.Compute.Models.KeyVaultAndSecretReference
    $encryptionSettingsElement.DiskEncryptionKey.SourceVault = New-Object Microsoft.Azure.Management.Compute.Models.SourceVault
    $encryptionSettingsElement.DiskEncryptionKey.SourceVault.Id = $keyVaultId
    $encryptionSettingsElement.DiskEncryptionKey.SecretUrl = $dekUrl
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettings = New-Object System.Collections.Generic.List[Microsoft.Azure.Management.Compute.Models.EncryptionSettingsElement]
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettings.Add($encryptionSettingsElement)
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettingsVersion = "1.1"
    Update-AzDisk -ResourceGroupName "testvault" -DiskName $obj.'properties.StorageProfile'.osDisk.name -DiskUpdate $diskupdateconfig
    

    机密可用并且在 OS 磁盘上设置加密详细信息之后,若要附加已还原的托管磁盘,请参阅使用 PowerShell 将数据磁盘附加到 Windows VMAfter the secrets are available and the encryption details are set on the OS disk, to attach the restored managed disks, see Attach a data disk to a Windows VM using PowerShell.

    • 不使用 Azure AD 的托管加密 VM(BEK 和 KEK) - 对于不使用 Azure AD 的托管加密 VM(使用 BEK 和 KEK 加密),如果源 keyVault/密钥/机密不可用,请使用从 Azure 备份恢复点还原未加密的虚拟机中的过程,将密钥和机密还原到密钥保管库。Managed and encrypted VMs without Azure AD (BEK and KEK) - For managed, encrypted VMs without Azure AD (encrypted using BEK & KEK), if source keyVault/key/secret are not available restore the key and secrets to key vault using the procedure in Restore an non-encrypted virtual machine from an Azure Backup recovery point. 然后执行以下脚本,在已还原的 OS 磁盘上设置加密详细信息(对于数据磁盘,不需要执行此步骤)。Then execute the following scripts to set encryption details on the restored OS disk (this step is not required for data disks). 可从已还原的 keyVault 提取 $dekurl 和 $kekurl。The $dekurl and $kekurl can be fetched from the restored keyVault.

    仅当源 keyVault/密钥/机密不可用时,才需要执行以下脚本。The following script needs to be executed only when the source keyVault/key/secret is not available.

    $dekUrl = "https://ContosoKeyVault.vault.azure.cn/secrets/ContosoSecret007/xx000000xx0849999f3xx30000003163"
    $kekUrl = "https://ContosoKeyVault.vault.azure.cn/keys/ContosoKey007/x9xxx00000x0000x9b9949999xx0x006"
    $keyVaultId = "/subscriptions/abcdedf007-4xyz-1a2b-0000-12a2b345675c/resourceGroups/ContosoRG108/providers/Microsoft.KeyVault/vaults/ContosoKeyVault"
    $diskupdateconfig = New-AzDiskUpdateConfig -EncryptionSettingsEnabled $true
    $encryptionSettingsElement = New-Object Microsoft.Azure.Management.Compute.Models.EncryptionSettingsElement
    $encryptionSettingsElement.DiskEncryptionKey = New-Object Microsoft.Azure.Management.Compute.Models.KeyVaultAndSecretReference
    $encryptionSettingsElement.DiskEncryptionKey.SourceVault = New-Object Microsoft.Azure.Management.Compute.Models.SourceVault
    $encryptionSettingsElement.DiskEncryptionKey.SourceVault.Id = $keyVaultId
    $encryptionSettingsElement.DiskEncryptionKey.SecretUrl = $dekUrl
    $encryptionSettingsElement.KeyEncryptionKey = New-Object Microsoft.Azure.Management.Compute.Models.KeyVaultAndKeyReference
    $encryptionSettingsElement.KeyEncryptionKey.SourceVault = New-Object Microsoft.Azure.Management.Compute.Models.SourceVault
    $encryptionSettingsElement.KeyEncryptionKey.SourceVault.Id = $keyVaultId
    $encryptionSettingsElement.KeyEncryptionKey.KeyUrl = $kekUrl
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettings = New-Object System.Collections.Generic.List[Microsoft.Azure.Management.Compute.Models.EncryptionSettingsElement]
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettings.Add($encryptionSettingsElement)
    $diskupdateconfig.EncryptionSettingsCollection.EncryptionSettingsVersion = "1.1"
    Update-AzDisk -ResourceGroupName "testvault" -DiskName $obj.'properties.StorageProfile'.osDisk.name -DiskUpdate $diskupdateconfig
    

    密钥/机密可用并且在 OS 磁盘上设置加密详细信息之后,若要附加已还原的托管磁盘,请参阅使用 PowerShell 将数据磁盘附加到 Windows VMAfter the key/secrets are available and the encryption details are set on the OS disk, to attach the restored managed disks, see Attach a data disk to a Windows VM using PowerShell.

  5. 设置网络设置。Set the Network settings.

    $nicName="p1234"
    $pip = New-AzPublicIpAddress -Name $nicName -ResourceGroupName "test" -Location "ChinaNorth" -AllocationMethod Dynamic
    $virtualNetwork = New-AzVirtualNetwork -ResourceGroupName "test" -Location "ChinaNorth" -Name "testvNET" -AddressPrefix 10.0.0.0/16
    $virtualNetwork | Set-AzVirtualNetwork
    $vnet = Get-AzVirtualNetwork -Name "testvNET" -ResourceGroupName "test"
    $subnetindex=0
    $nic = New-AzNetworkInterface -Name $nicName -ResourceGroupName "test" -Location "ChinaNorth" -SubnetId $vnet.Subnets[$subnetindex].Id -PublicIpAddressId $pip.Id
    $vm=Add-AzVMNetworkInterface -VM $vm -Id $nic.Id
    
  6. 创建虚拟机。Create the virtual machine.

    New-AzVM -ResourceGroupName "test" -Location "ChinaNorth" -VM $vm
    
  7. 推送 ADE 扩展。Push ADE extension. 如果未推送 ADE 扩展,则数据磁盘将标记为未加密,因此必须执行以下步骤:If the ADE extensions are not pushed, then the data disks will be marked as unencrypted, so it is mandatory for the steps below to be executed:

    • 对于使用 Azure AD 的 VM - 可使用以下命令来手动启用数据磁盘的加密。For VM with Azure AD - Use the following command to manually enable encryption for the data disks

      仅限 BEKBEK only

      Set-AzVMDiskEncryptionExtension -ResourceGroupName $RG -VMName $vm.Name -AadClientID $aadClientID -AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId -VolumeType Data
      

      BEK 和 KEKBEK and KEK

      Set-AzVMDiskEncryptionExtension -ResourceGroupName $RG -VMName $vm.Name -AadClientID $aadClientID -AadClientSecret $aadClientSecret -DiskEncryptionKeyVaultUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId  -KeyEncryptionKeyUrl $kekUrl -KeyEncryptionKeyVaultId $keyVaultId -VolumeType Data
      
    • 对于不使用 Azure AD 的 VM - 可使用以下命令来手动启用数据磁盘的加密。For VM without Azure AD - Use the following command to manually enable encryption for the data disks.

      如果在执行该命令期间系统要求提供 AADClientID,则你需要更新 Azure PowerShell。If during the command execution it asks for AADClientID, then you need to update your Azure PowerShell.

      仅限 BEKBEK only

      Set-AzVMDiskEncryptionExtension -ResourceGroupName $RG -VMName $vm.Name -DiskEncryptionKeyVaultUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId -SkipVmBackup -VolumeType "All"
      

      BEK 和 KEKBEK and KEK

      Set-AzVMDiskEncryptionExtension -ResourceGroupName $RG -VMName $vm.Name -DiskEncryptionKeyVaultUrl $dekUrl -DiskEncryptionKeyVaultId $keyVaultId -KeyEncryptionKeyUrl $kekUrl -KeyEncryptionKeyVaultId $keyVaultId -SkipVmBackup -VolumeType "All"
      

备注

确保手动删除在加密 VM 还原磁盘过程中创建的 JASON 文件。Ensure to manually delete the JASON files created as part of encrypted VM restore disk process.

从 Azure VM 备份还原文件Restore files from an Azure VM backup

除了可以还原磁盘以外,还可以从 Azure VM 备份还原单个文件。In addition to restoring disks, you can also restore individual files from an Azure VM backup. 还原文件功能提供了对恢复点中的所有文件的访问权限。The restore files functionality provides access to all files in a recovery point. 可以像对普通文件那样通过文件资源管理器管理这些文件。Manage the files via File Explorer as you would for normal files.

从 Azure VM 备份还原文件的基本步骤是:The basic steps to restore a file from an Azure VM backup are:

  • 选择 VMSelect the VM
  • 选择恢复点Choose a recovery point
  • 装载恢复点的磁盘Mount the disks of recovery point
  • 复制所需的文件Copy the required files
  • 卸载磁盘Unmount the disk

选择 VMSelect the VM

若要获取用于标识正确备份项的 PowerShell 对象,请从保管库中的容器开始,按对象层次结构进行操作。To get the PowerShell object that identifies the right backup item, start from the container in the vault, and work your way down the object hierarchy. 若要选择代表 VM 的容器,请使用 Get-AzRecoveryServicesBackupContainer cmdlet,然后通过管道将其传递给 Get-AzRecoveryServicesBackupItem cmdlet。To select the container that represents the VM, use the Get-AzRecoveryServicesBackupContainer cmdlet and pipe that to the Get-AzRecoveryServicesBackupItem cmdlet.

$namedContainer = Get-AzRecoveryServicesBackupContainer  -ContainerType "AzureVM" -Status "Registered" -FriendlyName "V2VM" -VaultId $targetVault.ID
$backupitem = Get-AzRecoveryServicesBackupItem -Container $namedContainer  -WorkloadType "AzureVM" -VaultId $targetVault.ID

选择恢复点Choose a recovery point

使用 Get-AzRecoveryServicesBackupRecoveryPoint cmdlet 列出备份项的所有恢复点。Use the Get-AzRecoveryServicesBackupRecoveryPoint cmdlet to list all recovery points for the backup item. 然后选择要还原的恢复点。Then choose the recovery point to restore. 如果不确定要使用的恢复点,最好选择列表中最新的 RecoveryPointType = AppConsistent 恢复点。If you are unsure which recovery point to use, it is a good practice to choose the most recent RecoveryPointType = AppConsistent point in the list.

在以下脚本中,变量 $rp 是一个数组,其中包含所选备份项在过去七天的恢复点。In the following script, the variable, $rp, is an array of recovery points for the selected backup item, from the past seven days. 该数组按时间进行反向排序,以最新的恢复点作为索引 0。The array is sorted in reverse order of time with the latest recovery point at index 0. 使用标准 PowerShell 数组索引选取恢复点。Use standard PowerShell array indexing to pick the recovery point. 在示例中,$rp[0] 选择最新的恢复点。In the example, $rp[0] selects the latest recovery point.

$startDate = (Get-Date).AddDays(-7)
$endDate = Get-Date
$rp = Get-AzRecoveryServicesBackupRecoveryPoint -Item $backupitem -StartDate $startdate.ToUniversalTime() -EndDate $enddate.ToUniversalTime() -VaultId $targetVault.ID
$rp[0]

输出类似于以下示例:The output is similar to the following example:

RecoveryPointAdditionalInfo :
SourceVMStorageType         : NormalStorage
Name                        : 15260861925810
ItemName                    : VM;iaasvmcontainer;RGName1;V2VM
RecoveryPointId             : /subscriptions/XX/resourceGroups/ RGName1/providers/Microsoft.RecoveryServices/vaults/testvault/backupFabrics/Azure/protectionContainers/IaasVMContainer;iaasvmcontainer;RGName1;V2VM/protectedItems/VM;iaasvmcontainer; RGName1;V2VM/recoveryPoints/15260861925810
RecoveryPointType           : AppConsistent
RecoveryPointTime           : 4/23/2016 5:02:04 PM
WorkloadType                : AzureVM
ContainerName               : IaasVMContainer;iaasvmcontainer; RGName1;V2VM
ContainerType               : AzureVM
BackupManagementType        : AzureVM

装载恢复点的磁盘Mount the disks of recovery point

请使用 Get-AzRecoveryServicesBackupRPMountScript cmdlet 获取用于装载恢复点的所有磁盘的脚本。Use the Get-AzRecoveryServicesBackupRPMountScript cmdlet to get the script to mount all the disks of the recovery point.

备注

这些磁盘作为 iSCSI 附加磁盘装载到运行此脚本的计算机中。The disks are mounted as iSCSI attached disks to the machine where the script is run. 装载是即时发生的,并且不会产生任何费用。Mounting occurs immediately, and you don't incur any charges.

Get-AzRecoveryServicesBackupRPMountScript -RecoveryPoint $rp[0] -VaultId $targetVault.ID

输出类似于以下示例:The output is similar to the following example:

OsType  Password        Filename
------  --------        --------
Windows e3632984e51f496 V2VM_wus2_8287309959960546283_451516692429_cbd6061f7fc543c489f1974d33659fed07a6e0c2e08740.exe

在要在它上面恢复文件的计算机上运行此脚本。Run the script on the machine where you want to recover the files. 若要执行该脚本,必须输入所提供的密码。To execute the script, you must enter the password provided. 附加磁盘后,使用 Windows 文件资源管理器浏览新的卷和文件。After the disks are attached, use Windows File Explorer to browse the new volumes and files. 有关详细信息,请参阅备份文章从 Azure 虚拟机备份恢复文件For more information, see the Backup article, Recover files from Azure virtual machine backup.

卸载磁盘Unmount the disks

复制所需的文件后,请使用 Disable-AzRecoveryServicesBackupRPMountScript 卸载磁盘。After the required files are copied, use Disable-AzRecoveryServicesBackupRPMountScript to unmount the disks. 请确保卸载磁盘,以便删除对恢复点的文件的访问权限。Be sure to unmount the disks so access to the files of the recovery point is removed.

Disable-AzRecoveryServicesBackupRPMountScript -RecoveryPoint $rp[0] -VaultId $targetVault.ID

后续步骤Next steps

如果你更愿意使用 PowerShell 来处理 Azure 资源,请查看 PowerShell 文章:为 Windows Server 部署和管理备份If you prefer to use PowerShell to engage with your Azure resources, see the PowerShell article, Deploy and Manage Backup for Windows Server. 如果管理 DPM 备份,请参阅为 DPM 部署和管理备份If you manage DPM backups, see the article, Deploy and Manage Backup for DPM.