I am trying to write to a powershell script to validate the Resource Group is exist or not.
Conditions-
Check the resource group (myrg) is already exist in azure subscription.
If "condition 1" is FALSE then Create a Resource Group (myrg) Else append 2 digits to the Resource Group name. e.g. (myrg01)
Check the (myrg01)resource group exist in azure subscription.
If "condition 3" is FALSE then Create a Resource Group (myrg01) Else increment the last digit by one for Resource Group name. e.g. (myrg02)
Check the (myrg02) resource group exist in azure subscription.
If "condition 5" is FALSE then Create a Resource Group (myrg02) Else increment the last digit by one for Resource Group name. e.g. (myrg03) and so on.........
Below is the code which i have written so far and unable to create a desired loop.
$rgname= "myrg"
Get-AzResourceGroup -Name $rgname -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notPresent){
Write-Host "ResourceGroup doesn't exist, Creating resource group"
$createRG= New-AzResourceGroup -Name $rgname -Location $region -Tag $tag
Write-Host $rgname
}
else{
$countcontent = $countcontent + 1
$counter = [int]$countcontent
++$counter
$countString = "{0:d2}" -f ($counter)
Write-Host "ResourceGroup $rgname already exist, Generating a new name for Resource Group"
$rgname= $rgname + $countString
Get-AzResourceGroup -Name $rgname -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notpresent){
$createRG= New-AzResourceGroup -Name $rgname -Location $region -Tag $tag
Write-Host $rgname
Clear-Variable countcontent
Clear-Variable counter
Clear-Variable countString
}
}