本文介绍了验证Azure资源组是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写入Powershell脚本以验证资源组是否存在.

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

条件-

  1. 检查azure订阅中的资源组(myrg)已经存在.

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

如果条件1"为FALSE,则创建资源组(myrg),否则在资源组名称后附加2位数字.例如(myrg01)

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

检查Azure订阅中是否存在(myrg01)资源组.

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

如果条件3"为FALSE,则创建资源组(myrg01),否则将资源组名称的最后一位数字递增1.例如(myrg02)

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)

检查Azure订阅中是否存在(myrg02)资源组.

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

如果条件5"为FALSE,则创建资源组(myrg02),否则将资源组名称的最后一位数字递增1.例如(myrg03)等等......

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

推荐答案

解决方法

$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"

这篇关于验证Azure资源组是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 16:32