List Virtual Machine in an azure site recovery plan

62 Views Asked by At

I need to add some pre/post action to an Azure Site Recovery plan against the vm in the recovery plan. I have the following code, however, no VMs are listed. Please what can I do to enhance the code.

param (
    [parameter(Mandatory=$true)]
    [Object]$RecoveryPlanContext
)


$ErrorActionPreference = 'Continue'
$VerbosePreference = 'SilentlyContinue'
Disconnect-AzAccount -ErrorAction SilentlyContinue | Out-Null
Clear-AzContext -Scope Process -ErrorAction SilentlyContinue | Out-Null
Clear-AzContext -Scope CurrentUser -ErrorAction SilentlyContinue | Out-Null
Disable-AzContextAutosave –Scope Process | Out-Null



# Login to Azure 
Connect-AzAccount -Identity

Write-Verbose "getting vmmap object"
$VMMapColl = $RecoveryPlanContextObj.VmMap

$VMCollection = @()

$VMinfo = $RecoveryPlanContext.VmMap | Get-Member | Where-Object MemberType -EQ NoteProperty | select -ExpandProperty Name
$vmMap = $RecoveryPlanContext.VmMap
    foreach($VMID in $VMinfo)
    {
        $VMCollection += $VM              
         
        }

$CollectionCount = $VMCollection.Count
Write-Output "Collection Count: $CollectionCount" 
#Returning Collection
$VMCollection.RoleName
1

There are 1 best solutions below

3
Venkat V On

List Virtual Machine in an azure site recovery plan

Here is the updated PowerShell script to list all VMs in the Azure Site Recovery Plan.

    $ResourceGroup = "<RG_name"
    $VaultName = "<vault_name>"
    # Get the ASR vault
    $vault = Get-AzRecoveryServicesVault -ResourceGroupName $ResourceGroup -Name $VaultName
    
    # Set the context of the vault. This is required for all future commands
    Set-AzRecoveryServicesAsrVaultContext -Vault $vault
    
    # List all the items that are in a protected state by friendly name and resource ID
    
    $fabrics = Get-AzRecoveryServicesAsrFabric
       
        
    foreach ($fabric in $fabrics) {
                $container = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $fabric
                $protectItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $container
                $RecoveryPlan = Get-AzRecoveryServicesAsrRecoveryPlan | Where-Object {$_.name -eq "Service_Plan_Name"}
    
            if ($protectedItem.RecoveryFabricId -eq $RecoveryPlan.TargetServerId){
    
            Write-Host "Virtual Machine Name: $($protectedItems.FriendlyName)"
            Write-Host "VM ID: $($protectedItems.ID)"
            Write-Host "Protection State: $($protectedItems.ProtectionState)"
            Write-Host "============================="
        }
      }

This PowerShell script will list all VMs in a Service Plan and then add pre/post actions to an Azure Site Recovery plan as per your requirement.

Output:

enter image description here

Reference: How do you get a list of all the VMs in a Recovery Plan with powershell