Validate Azure Resource Group Exist or not

你。 提交于 2020-07-10 08:57:21

问题


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

回答1:


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"


来源:https://stackoverflow.com/questions/62444269/validate-azure-resource-group-exist-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!