I am creating an Azure Automation account having a powershell runbook. The script is simply looping over each VM in a resource group and deleting all files under a particular folder.
$ResourceGroup = '<<myResourceGroup>>'
$TargetDir = '<targetDirectoryPath/.'
$TargetCommand = 'rm -rfv ' + $TargetDir
try
{
$message = Connect-AzAccount -Identity
$myAzureVMs = Get-AzVM -ResourceGroupName $ResourceGroup -status | Where-Object {$_.PowerState -eq "VM running" -and $_.StorageProfile.OSDisk.OSType -eq "Linux"}
if($myAzureVMs.Name.Count -gt 1)
{
For($val = 0; $val -le $myAzureVMs.Name.Count-1; $val++)
{
# the script hangs here
$message = Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroup -Name $myAzureVMs.Name[$val] -CommandId 'RunShellScript' -ScriptString $TargetCommand
}
}
Write-Output "DONE !!"
}
catch
{
Write-Error -Message $_.Exception
throw $_.Exception
}
The script is working fine but the issue is if a VM is not ok or has some connectivity problem then the script hangs just there. No error or exception is thrown. It just keeps waiting and eventually times out after hours.
My question is there any way to check if the VM can be connected or not (or any better solution) and then only the script should execute. I have also tried putting the Invoke-AzVMRunCommand inside a try-catch block to eat up the exception and to move to the next VM but in vain. It's simply hangs on to that VM and no exception thrown.