Search code examples
azurepowershellazure-powershellazure-resource-group

Validate Azure Resource Group Exist or not


I am trying to write to a powershell script to validate the Resource Group is exist or not.

Conditions-

  1. Check the resource group (myrg) is already exist in azure subscription.

  2. If "condition 1" is FALSE then Create a Resource Group (myrg) Else append 2 digits to the Resource Group name. e.g. (myrg01)

  3. Check the (myrg01)resource group exist in azure subscription.

  4. 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)

  5. Check the (myrg02) resource group exist in azure subscription.

  6. 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
   }
}

Solution

  • Got a workaround

    $rg="myrg"
    $Subscriptions = Get-AzSubscription
    $Rglist=@()
    foreach ($Subscription in $Subscriptions){
    $Rglist +=(Get-AzResourceGroup).ResourceGroupName
    }
    $rgfinal=$rg
    $i=1
    while($rgfinal -in $Rglist){
    $rgfinal=$rg +"0" + $i++
    }
    Write-Output $rgfinal
    Set-AzContext -Subscription "Subscription Name"
    $createrg= New-AzResourceGroup -Name $rgfinal -Location "location"