Validate Azure Resource Group Exist or not
Asked Answered
F

2

0

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
   }
}
Fuse answered 18/6, 2020 at 7:8 Comment(0)
F
0

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"
Fuse answered 18/6, 2020 at 12:51 Comment(0)
V
0
 #This code will check the Azure Resource Group existence 
 #you can create non-exist Resource Group    

    $rgName = Read-Host "RG Name"
    $rgGroup=Get-AzResourceGroup
    
    while ($rgGroup.ResourceGroupName -eq $rgName)
    {
        Write-Output "RG Existed"
        $rgName = Read-Host "New RG Name Plz"
     }
    
    if($rgGroup.ResourceGroupName -ne $rgName)
    {
      New-AzResourceGroup -Name $rgName -Location "East US"
     }
    Write-Output "$rgName RG Created"
Vladimir answered 15/2 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.