Search code examples
powershellresourcesazure-resource-group

Creating a loop to create a new resource group in Powershell


I need to create a loop that will check if a resource group name is taken or not, and if not create a new resource group with that name.

This is the code I used to try and complete this

do
{
    $rg = Read-Host -Prompt "What would you like to name the new Resource Group"
    if (!(Get-AzureRmResourceGroup -ResourceGroupName $rg -ErrorAction Ignore)) 
    {
        New-AzureRmResourceGroup -ResourceGroupName $rg -Location "West Europe"
    } 
    else {
        $rg = Read-Host -Prompt "Resouce Group name not available, please select another"
        New-AzureRmResourceGroup -ResourceGroupName $rg -Location "West Europe"
    }

}
while (!(Get-AzureRmResourceGroup -ResourceGroupName $rg -ErrorAction Ignore))

Solution

  • What you said: "I want a user to enter a number, and keep entering if until they enter something > 10".

    What you coded: "Enter a number, test if it's < 10 and prompt again. Don't test this one, go with it without testing it. Now loop all of that."

    do
    {
        # coming round from a previous loop, $num exists, indicating this is a retry.
        if ($null -ne $num) { Write-Host "Sorry, try again" }
    
        [int]$num = Read-Host "Enter a number"
    
    } until ($num -gt 10)