Powershell to Stop Azure backups - azure

So i'm running into a Bad Request error using the Stop-AzRecoveryServicesBackupJob powershell command. The documentation isn't helpfull as it only requires -JobID $Job.InstanceId as a parameter. BUT, InstanceId doesn't exist. JobID does, but returns the bad request error.
My code: The bad request is on Stop-AzRecoveryServicesBackupJob -JobID $BackupJob.JobId
#get RSV
$myVault = Get-AzRecoveryServicesVault -ResourceGroupName $myResourceGroup -Name $vaultName
#Disable soft delete on RSV
$myVault.ID | Set-AzRecoveryServicesVaultProperty -SoftDeleteFeatureState Disable | Out-Null
$BackupJob = $myVault.ID | Get-AzRecoveryServicesBackupJob -Operation Backup
Stop-AzRecoveryServicesBackupJob -JobID $BackupJob.JobId
Error msg:
Stop-AzRecoveryServicesBackupJob : Cannot cancel the job. Only in progress jobs can be cancelled. Please attempt cancellation only on an in progress job.
At C:\Users\azureuser\Documents\WindowsPowerShell\temp.ps1:20 char:1
Stop-AzRecoveryServicesBackupJob -Job $BackupJob
+ CategoryInfo : InvalidOperation: (:) [Stop-AzRecoveryServicesBackupJob], CloudException
+ FullyQualifiedErrorId : BMSUserErrorJobNotInProgressToCancel,Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.StopAzureRmRecoveryServicesBackupJo
b

So following up on the "In Progress Job" Stop-AzRecoveryServicesBackupJob will only stop the job while it is in progress. If you want to stop the backup of jobs that aren't currently in progress you need to use Disable-AzRecoveryServicesBackupProtection. No exactly self explanitory.
correct code :
$Cont = Get-AzRecoveryServicesBackupContainer -ContainerType AzureVM -Status Registered
$PI = Get-AzRecoveryServicesBackupItem -Container $Cont[0] -WorkloadType AzureVM
Disable-AzRecoveryServicesBackupProtection -Item $PI[0]
This will change the status to disabled. (Even though the choice manually is "Stop Backup") 🤷‍♂️

Related

Set-AzRecoveryServicesAsrVaultContext : Operation failed

Below script works for one recovery vault but fails for another.
Script
$Sub = Get-AzSubscription -SubscriptionName ''
$context = $Sub | Set-AzContext
$rv = Get-AzRecoveryServicesVault -ResourceGroupName '' -Name ''
Set-AzRecoveryServicesAsrVaultContext -Vault $rv -defaultprofile $context
Error
Set-AzRecoveryServicesAsrVaultContext : Operation failed.
Download vault credential file using cmdlet Get-AzRecoveryServicesVaultSettingsFile and Import-AzRecoveryServicesAsrVaultSettingsFile
At line:1 char:1
+ Set-AzRecoveryServicesAsrVaultContext -Vault $rv -defaultprofile $con
+ CategoryInfo : CloseError: (:) [Set-AzRecoveryServicesAsrVaultContext], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.RecoveryServices.SiteRecover
Hi the issue was related to vnet configuration. now it is resolved.
error was was coming as data was not passing from one vnet to another.

Get-AzRecoveryServicesBackupItem : Cannot validate argument on parameter 'Container'. The argument is null or empty

I am working on this official tutorial from MS Azure team on Back up a virtual machine in Azure with PowerShell. But while running runbook from Start a backup job section, I get the error shown below. Question: What I may be missing here, and how the issue can be fixed?
Following lines runs fine:
PS C:\Users\myUserName> $vault = Get-AzRecoveryServicesVault -ResourceGroupName "rg-cs-ansible1" -Name "myRecoveryServicesVault"
>> $backupcontainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -Status "Registered" -FriendlyName "myVM" -VaultId $vault.ID
But when I run the following line, I get the error shown below.
PS C:\Users\myUserName> $item = Get-AzRecoveryServicesBackupItem -Container $backupcontainer -WorkloadType AzureVM -VaultId $vault.ID
Error
Get-AzRecoveryServicesBackupItem : Cannot validate argument on parameter 'Container'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At line:2 char:16
+ -Container $backupcontainer `
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-AzRecoveryServicesBackupItem], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlet
s.GetAzureRmRecoveryServicesBackupItem
Per my test, your commands work fine on my side. I can just reproduce your issue with a wrong VM name this command, even if your VM name is wrong, it will not give an error, but the $backupcontainer will be null, it will cause the error in the next command.
$backupcontainer = Get-AzRecoveryServicesBackupContainer -ContainerType "AzureVM" -Status "Registered" -FriendlyName "myVM" -VaultId $vault.ID
So in your case, please make sure myVM is the correct VM name used for -FriendlyName parameter.

The remote server returned an error: (403) Forbidden. At C:\Program Files\WindowsPowerShell\Modules\CosmosDB\3.1.0.293\CosmosDB.psm1

I developed the PowerShell script for creating Database and Collection in the Azure Cosmos DB.
#region Parameters
$connectionString='XXXXXXXXXXXXXXXXX=='
$accountName='demo-account-01'
$databaseName='demo-db-01'
$collectionName='demo-collection-01'
#endregion
#region Login into Azure using Interactive Mode
# sign in
Write-Host "Logging in...";
Connect-AzAccount
#Set the current azure subscription
Select-AzSubscription -subscription 'Visual Studio Ultimate with MSDN'
#endregion
#region Create Collection and insert some data into it
$key = Get-CosmosDbAccountMasterKey -Name $accountName -ResourceGroupName 'Demo'
$cosmosDbContext = New-CosmosDbContext -Account $accountName -Key $key
New-CosmosDbDatabase -Context $cosmosDbContext -Id $databaseName
#New-CosmosDbCollection -Context $cosmosDbContext -Id $collectionName -PartitionKey 'account' -OfferThroughput 50000 -Database $databaseName
New-CosmosDbCollection -Context $cosmosDbContext -Id $collectionName -OfferThroughput 2500 -Database $databaseName
#endregion
But when run the above script I am getting the error like shown in below:
Invoke-WebRequest : The remote server returned an error: (403) Forbidden. At C:\Program Files\WindowsPowerShell\Modules\CosmosDB\3.1.0.293\CosmosDB.psm1:5275 char:30 + ... $requestResult = Invoke-WebRequest #invokeWebRequestParameters + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
So, can anyone suggest me how to resolve the issue?
You need to add your IP address in the Firewall and virtual networks, then it will work.

Starting Azure Vm in parallel with runbook throws InvalidOperationException

I'm trying to use Azure runbooks to start virtual machines with a specified tag. I use powershell workflow so i can start them i parallel.
The code below works, but it always have problem starting one random virtual machine. This is the exception:
Start-AzureRmVM : Collection was modified; enumeration operation may
not execute.
CategoryInfo : CloseError: (:) [Start-AzureRmVM], InvalidOperationException
I thought $TaggedResourcesList = #($Resources) would enumerate the list and make modifications allowed?
workflow StartUpParallel
{
$Resources = Find-AzureRmResource -TagName Startup -TagValue PreWork
$TaggedResourcesList = #($Resources)
Foreach -Parallel ( $vm in $TaggedResourcesList )
{
if($vm.ResourceType -eq "Microsoft.Compute/virtualMachines")
{
Start-AzureRmVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name
}
}
}
Has anyone else had this problem?

Get-AzureRmRecoveryServicesBackupContainer : Requested value 'NotRegistered' was not found

I am using below command in Azure Automation Powershell script to get status of Recovery Services container - it simply checks if a VM is registered for backup.
Get-AzureRmRecoveryServicesVault -Name $AzureRecoveryServicesName | Set-AzureRmRecoveryServicesVaultContext
$BackupStatus = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureVM -FriendlyName $VirtualMachineName -ResourceGroupName $ResourceGroupName
If a VM is not registered it throws an error and $BackupStatus is empty:
Get-AzureRmRecoveryServicesBackupContainer : Requested value 'NotRegistered' was not found.
At line:53 char:21
... kupStatus = Get-AzureRmRecoveryServicesBackupContainer -ContainerType ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Get-AzureRmReco...BackupContainer], ArgumentException
FullyQualifiedErrorId :
Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.GetAzureRmRecoveryServicesBackupContainer
And if it is already registered I get $BackupStatus = Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models.AzureVmContainer.
I've tried:
$BackupStatus = (Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureVM -FriendlyName $VirtualMachineName -ResourceGroupName $ResourceGroupName).Status
But then the only difference is that I get $BackupStatus = Registered when VM is already in a container but same error occurs when VM is not registered.
What is the proper way to check if a VM is registered for backup or not? I am ok with what I'm getting - I can handle $BackupStatus values in a script - but I don't want this error message to show.
Strange thing is that in Powershell on PC with same Azure modules versions loaded (AzureRM​.RecoveryServices​.Backup 2.5.0) as in Automation Account I am getting a different behavior:
PS C:\windows\system32> $BackupStatus = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureVM -FriendlyName $VirtualMachineName -ResourceGroupName $ResourceGroupName
PS C:\windows\system32> $BackupStatus
Name ResourceGroupName Status ContainerType
---- ----------------- ------ -------------
UbuntuBckptest rhel68128 Registered AzureVM
It returns an object instead of a string.
If you want to set $BackupStatus value according to Get-AzureRmRecoveryServicesBackupContainer command executed result. We could put the Get-AzureRmRecoveryServicesBackupContainer in try...catch.
The following just the code sample
$BackupStatus;
try
{
$BackupStatus=Get-AzureRmRecoveryServicesBackupContainer
}
catch
{
# we can add condition for example : if($BackupStatus.Contains("NotRegistered"))
$BackupStatus = "NotRegistered"
}
# we can add condition :get the type of $BackupStatus for example :if($BackupStatus.GetType().Name.equals("String"))`
$BackupStatus = "Registered"

Resources