使用 PowerShell 和 Azure 资源管理器对 Hyper-V VM 设置到 Azure 的灾难恢复Set up disaster recovery to Azure for Hyper-V VMs using PowerShell and Azure Resource Manager

Azure Site Recovery 有助于业务连续性和灾难恢复 (BCDR) 策略,因为它可以协调 Azure 虚拟机 (VM)、本地 VM 和物理服务器的复制、故障转移和恢复。Azure Site Recovery contributes to your business continuity and disaster recovery (BCDR) strategy by orchestrating replication, failover, and recovery of Azure virtual machines (VMs), and on-premises VMs and physical servers.

本文介绍如何结合使用 Windows PowerShell 和 Azure 资源管理器将 Hyper-V VM 复制到 Azure。This article describes how to use Windows PowerShell, together with Azure Resource Manager, to replicate Hyper-V VMs to Azure. 本文中使用的示例演示如何将在 Hyper-V 主机上运行的单个 VM 复制到 Azure。The example used in this article shows you how to replicate a single VM running on a Hyper-V host, to Azure.


本文进行了更新,以便使用新的 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.

Azure PowerShellAzure PowerShell

Azure PowerShell 提供用于通过 Windows PowerShell 管理 Azure 的 cmdlet。Azure PowerShell provides cmdlets to manage Azure using Windows PowerShell. 适用于 Azure 资源管理器的 Azure PowerShell 随附 Site Recovery PowerShell cmdlet,有助于保护和恢复 Azure 中的服务器。Site Recovery PowerShell cmdlets, available with Azure PowerShell for Azure Resource Manager, help you protect and recover your servers in Azure.

尽管无需成为一名 PowerShell 专家就可以使用本文章,但你还是需要理解诸如模块、cmdlet 和会话等基本概念。You don't need to be a PowerShell expert to use this article, but you do need to understand basic concepts, such as modules, cmdlets, and sessions. 有关详细信息,请参阅 PowerShell 文档将 Azure PowerShell 与 Azure 资源管理器配合使用For more information, see the PowerShell Documentation and Using Azure PowerShell with Azure Resource Manager.


参与云解决方案提供商 (CSP) 计划的 Azure 合作伙伴可以根据各自的 CSP 订阅(租户订阅)对客户服务器的保护措施进行配置和管理。Azure partners in the Cloud Solution Provider (CSP) program can configure and manage protection of customer servers to their respective CSP subscriptions (tenant subscriptions).

准备工作Before you start

确保已满足以下先决条件:Make sure you have these prerequisites in place:

此外,本文中提及的特定示例要求满足以下先决条件:In addition, the specific example described in this article has the following prerequisites:

  • 一台运行 Windows Server 2012 R2 或 Microsoft Hyper-V Server 2012 R2 的 Hyper-V 主机,其中包含一个或多个 VM。A Hyper-V host running Windows Server 2012 R2 or Microsoft Hyper-V Server 2012 R2 containing one or more VMs. Hyper-V 服务器应直接或通过代理连接到 Internet。Hyper-V servers should be connected to the Internet, either directly or through a proxy.
  • 要复制的 VM 应符合这些先决条件The VMs you want to replicate should conform with these prerequisites.

步骤 1:登录到 Azure 帐户Step 1: Sign in to your Azure account

  1. 打开 PowerShell 控制台,并运行以下命令以登录到 Azure 帐户。Open a PowerShell console and run this command to sign in to your Azure account. 此 cmdlet 会打开一个网页,提示输入帐户凭据:Connect-AzAccount -Environment AzureChinaCloudThe cmdlet brings up a web page prompts you for your account credentials: Connect-AzAccount -Environment AzureChinaCloud.

    • 或者,可以使用 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're a 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"
  2. 由于一个帐户可以有多个订阅,因此请将要使用的订阅与帐户关联在一起:Associate the subscription you want to use with the account, since an account can have several subscriptions:

    Set-AzContext -Subscription $SubscriptionName
  3. 使用以下命令验证订阅是否已注册,以便将 Azure 提供程序用于恢复服务和 Site Recovery:Verify that your subscription is registered to use the Azure providers for Recovery Services and Site Recovery, using these commands:

    Get-AzResourceProvider -ProviderNamespace  Microsoft.RecoveryServices
  4. 验证命令输出中是否将“RegistrationState”设置为“已注册”,如果是,则可继续执行步骤 2********。Verify that in the command output, the RegistrationState is set to Registered, you can proceed to Step 2. 否则,需要通过运行以下命令注册订阅中缺失的提供程序:If not, you should register the missing provider in your subscription, by running these commands:

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

    Get-AzResourceProvider -ProviderNamespace  Microsoft.RecoveryServices

步骤 2:设置保管库Step 2: Set up the vault

  1. 创建一个可在其中创建保管库的 Azure 资源管理器资源组,或者使用现有资源组。Create an Azure Resource Manager resource group in which to create the vault, or use an existing resource group. 创建新资源组,如下所示。Create a new resource group as follows. $ResourceGroupName 变量包含需要创建的资源组的名称,$Geo 变量包含要在其中创建资源组的 Azure 区域(例如“中国北部”)。The $ResourceGroupName variable contains the name of the resource group you want to create, and the $Geo variable contains the Azure region in which to create the resource group (for example, "China North").

    New-AzResourceGroup -Name $ResourceGroupName -Location $Geo
  2. 若要获取订阅中资源组的列表,请运行 Get-AzResourceGroup cmdlet。To obtain a list of resource groups in your subscription, run the Get-AzResourceGroup cmdlet.

  3. 创建如下所示的新的 Azure 恢复服务保管库:Create a new Azure Recovery Services vault as follows:

    $vault = New-AzRecoveryServicesVault -Name <string> -ResourceGroupName <string> -Location <string>

可以使用 Get-AzRecoveryServicesVault cmdlet 检索现有保管库的列表。You can retrieve a list of existing vaults with the Get-AzRecoveryServicesVault cmdlet.

步骤 3:设置恢复服务保管库上下文Step 3: Set the Recovery Services vault context

设置保管库上下文,如下所示:Set the vault context as follows:

Set-AzRecoveryServicesAsrVaultContext -Vault $vault

步骤 4:创建 Hyper-V 站点Step 4: Create a Hyper-V site

  1. 创建新的 Hyper-V 站点,如下所示:Create a new Hyper-V site as follows:

    $sitename = "MySite"                #Specify site friendly name
    New-AzRecoveryServicesAsrFabric -Type HyperVSite -Name $sitename
  2. 此 cmdlet 会启动一个创建该站点所需的站点恢复作业,并返回一个站点恢复作业对象。This cmdlet starts a Site Recovery job to create the site, and returns a Site Recovery job object. 等待作业完成,并验证作业已成功完成。Wait for the job to complete and verify that the job completed successfully.

  3. 使用 Get-AzRecoveryServicesAsrJob cmdlet 检索作业对象,并查看作业的当前状态。Use the Get-AzRecoveryServicesAsrJob cmdlet to retrieve the job object, and check the current status of the job.

  4. 生成和下载站点的注册密钥,如下所示:Generate and download a registration key for the site, as follows:

    $SiteIdentifier = Get-AzRecoveryServicesAsrFabric -Name $sitename | Select-Object -ExpandProperty SiteIdentifier
    $path = Get-AzRecoveryServicesVaultSettingsFile -Vault $vault -SiteIdentifier $SiteIdentifier -SiteFriendlyName $sitename
  5. 将已下载的密钥复制到 Hyper-V 主机。Copy the downloaded key to the Hyper-V host. 需要通过该密钥将 Hyper-V 主机注册到站点。You need the key to register the Hyper-V host to the site.

步骤 5:安装提供程序和代理Step 5: Install the Provider and agent

  1. Microsoft 下载最新版提供程序的安装程序。Download the installer for the latest version of the Provider from Microsoft.

  2. 在 Hyper-V 主机上运行安装程序。Run the installer on the Hyper-V host.

  3. 在安装结束时继续执行注册步骤。At the end of the installation continue to the registration step.

  4. 在系统提示时提供下载的密钥,然后完成 Hyper-V 主机的注册过程。When prompted, provide the downloaded key, and complete registration of the Hyper-V host.

  5. 验证 Hyper-V 主机是否已注册到站点,如下所示:Verify that the Hyper-V host is registered to the site as follows:

    $server = Get-AzRecoveryServicesAsrFabric -Name $siteName | Get-AzRecoveryServicesAsrServicesProvider -FriendlyName $server-friendlyname

如果运行的是 Hyper-V 核心服务器,请下载安装程序文件并执行以下操作:If you're running a Hyper-V core server, download the setup file and follow these steps:

  1. 运行以下命令,将 AzureSiteRecoveryProvider.exe 中的文件提取到本地目录:Extract the files from AzureSiteRecoveryProvider.exe to a local directory by running this command:

    AzureSiteRecoveryProvider.exe /x:. /q
  2. 运行以下命令:Run the following command:

    .\setupdr.exe /i

    结果记录到 %ProgramData%\ASRLogs\DRASetupWizard.logResults are logged to %ProgramData%\ASRLogs\DRASetupWizard.log.

  3. 运行此命令注册服务器:Register the server by running this command:

    cd  C:\Program Files\Microsoft Azure Site Recovery Provider\DRConfigurator.exe" /r /Friendlyname "FriendlyName of the Server" /Credentials "path to where the credential file is saved"

步骤 6:创建复制策略Step 6: Create a replication policy

在开始前,指定的存储帐户应与保管库处于同一 Azure 区域,并且应已启用异地复制。Before you start, the storage account specified should be in the same Azure region as the vault, and should have geo-replication enabled.

  1. 创建复制策略,如下所示:Create a replication policy as follows:

    $ReplicationFrequencyInSeconds = "300";        #options are 30,300,900
    $PolicyName = "replicapolicy"
    $Recoverypoints = 6                    #specify the number of recovery points
    $storageaccountID = Get-AzStorageAccount -Name "mystorea" -ResourceGroupName "MyRG" | Select-Object -ExpandProperty Id
    $PolicyResult = New-AzRecoveryServicesAsrPolicy -Name $PolicyName -ReplicationProvider "HyperVReplicaAzure" -ReplicationFrequencyInSeconds $ReplicationFrequencyInSeconds -NumberOfRecoveryPointsToRetain $Recoverypoints -ApplicationConsistentSnapshotFrequencyInHours 1 -RecoveryAzureStorageAccountId $storageaccountID
  2. 检查返回的作业,确保复制策略创建成功。Check the returned job to ensure that the replication policy creation succeeds.

  3. 检索对应于该站点的保护容器,如下所示:Retrieve the protection container that corresponds to the site, as follows:

    $protectionContainer = Get-AzRecoveryServicesAsrProtectionContainer
  4. 将保护容器与复制策略相关联,如下所示:Associate the protection container with the replication policy, as follows:

    $Policy = Get-AzRecoveryServicesAsrPolicy -FriendlyName $PolicyName
    $associationJob = New-AzRecoveryServicesAsrProtectionContainerMapping -Name $mappingName -Policy $Policy -PrimaryProtectionContainer $protectionContainer[0]
  5. 等待关联作业成功完成。Wait for the association job to complete successfully.

  6. 检索保护容器映射。Retrieve the protection container mapping.

    $ProtectionContainerMapping = Get-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainer $protectionContainer

步骤 7:启用 VM 保护Step 7: Enable VM protection

  1. 检索与要保护的 VM 相对应的可保护项,如下所示:Retrieve the protectable item that corresponds to the VM you want to protect, as follows:

    $VMFriendlyName = "Fabrikam-app"          #Name of the VM
    $ProtectableItem = Get-AzRecoveryServicesAsrProtectableItem -ProtectionContainer $protectionContainer -FriendlyName $VMFriendlyName
  2. 保护 VM。Protect the VM. 如果要保护的 VM 有多个附加磁盘,则需使用 OSDiskName 参数指定操作系统磁盘。If the VM you're protecting has more than one disk attached to it, specify the operating system disk by using the OSDiskName parameter.

    $OSType = "Windows"          # "Windows" or "Linux"
    $DRjob = New-AzRecoveryServicesAsrReplicationProtectedItem -ProtectableItem $VM -Name $VM.Name -ProtectionContainerMapping $ProtectionContainerMapping -RecoveryAzureStorageAccountId $StorageAccountID -OSDiskName $OSDiskNameList[$i] -OS $OSType -RecoveryResourceGroupId $ResourceGroupID
  3. 等待 VM 在完成初始复制后进入受保护状态。Wait for the VMs to reach a protected state after the initial replication. 这可能需要一段时间,具体取决于诸如要复制的数据量和 Azure 的可用上游带宽等因素。This can take a while, depending on factors such as the amount of data to be replicated, and the available upstream bandwidth to Azure. 进入受保护状态后,更新作业状态和 StateDescription,如下所示:When a protected state is in place, the job State and StateDescription are updated as follows:

    PS C:\> $DRjob = Get-AzRecoveryServicesAsrJob -Job $DRjob
    PS C:\> $DRjob | Select-Object -ExpandProperty State
    PS C:\> $DRjob | Select-Object -ExpandProperty StateDescription
  4. 更新各种恢复属性(例如 VM 角色大小),以及进行故障转移后需要将 VM NIC 连接到的 Azure 网络。Update recovery properties (such as the VM role size) and the Azure network to which to attach the VM NIC after failover.

    PS C:\> $nw1 = Get-AzVirtualNetwork -Name "FailoverNw" -ResourceGroupName "MyRG"
    PS C:\> $VMFriendlyName = "Fabrikam-App"
    PS C:\> $rpi = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $protectionContainer -FriendlyName $VMFriendlyName
    PS C:\> $UpdateJob = Set-AzRecoveryServicesAsrReplicationProtectedItem -InputObject $rpi -PrimaryNic $VM.NicDetailsList[0].NicId -RecoveryNetworkId $nw1.Id -RecoveryNicSubnetName $nw1.Subnets[0].Name
    PS C:\> $UpdateJob = Get-AzRecoveryServicesAsrJob -Job $UpdateJob
    PS C:\> $UpdateJob | Select-Object -ExpandProperty state
    PS C:\> Get-AzRecoveryServicesAsrJob -Job $job | Select-Object -ExpandProperty state


如果希望复制到 Azure 中启用了 CMK 的托管磁盘,请使用 Az PowerShell 3.3.0 及更高版本执行以下步骤:If you wish to replicate to CMK enabled managed disks in Azure, do the following steps using Az PowerShell 3.3.0 onwards:

  1. 通过更新 VM 属性启用到托管磁盘的故障转移Enable failover to managed disks by updating VM properties
  2. 使用 Get-AzRecoveryServicesAsrReplicationProtectedItem cmdlet 获取受保护项的每个磁盘的磁盘 IDUse the Get-AzRecoveryServicesAsrReplicationProtectedItem cmdlet to fetch the disk ID for each disk of the protected item
  3. 使用 New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]" cmdlet 创建包含磁盘 ID 到磁盘加密集映射的字典对象。Create a dictionary object using New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]" cmdlet to contain the mapping of disk ID to disk encryption set. 这些磁盘加密集将由你在目标区域中预先创建。These disk encryption sets are to be pre-created by you in the target region.
  4. 通过在 DiskIdToDiskEncryptionSetMap 参数中传递字典对象,使用 Set-AzRecoveryServicesAsrReplicationProtectedItem cmdlet 更新 VM 属性。Update the VM properties using Set-AzRecoveryServicesAsrReplicationProtectedItem cmdlet by passing the dictionary object in DiskIdToDiskEncryptionSetMap parameter.

步骤 8:运行测试故障转移Step 8: Run a test failover

  1. 按如下所述运行测试故障转移:Run a test failover as follows:

    $nw = Get-AzVirtualNetwork -Name "TestFailoverNw" -ResourceGroupName "MyRG" #Specify Azure vnet name and resource group
    $rpi = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $protectionContainer -FriendlyName $VMFriendlyName
    $TFjob = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $VM -Direction PrimaryToRecovery -AzureVMNetworkId $nw.Id
  2. 验证是否在 Azure 中创建了测试 VM。Verify that the test VM is created in Azure. 在 Azure 中创建测试 VM 之后,暂停测试故障转移作业。The test failover job is suspended after creating the test VM in Azure.

  3. 若要清理并完成测试故障转移,请运行:To clean up and complete the test failover, run:

    $TFjob = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $rpi -Comment "TFO done"

后续步骤Next steps

详细了解 Azure Site Recovery 和 Azure 资源管理器 PowerShell cmdlet。Learn more about Azure Site Recovery with Azure Resource Manager PowerShell cmdlets.