Cannot see Resource group in Azure portal

1.6k Views Asked by At

Spoiler: I am new to Azure and Azure Powershell.

I started to learn Azure and Azure Powershell and my current self-given excercise was to write a script, which checks if a specifig resource group exist in Azure. If this specific resource group does not exist, then create one. So I started to write this script:

# Exit on error
$ErrorActionPreference = "Stop"

# Import module for Azure Rm
Import-Module AzureRM

# Connect with Azure
Connect-AzureRmAccount

# Define name of Resource group we want to create
$ResourceGroupTest = "ResourceGroupForStorageAccount"

# Check if ResourceGroup exists
Get-AzureRmResourceGroup -Name $ResourceGroupTest -ErrorVariable $NotPresent -ErrorAction SilentlyContinue

Write-Host "Start to check if Resource group '$($ResourceGroupTest)' exists..."
if ($NotPresent) {
    Write-Host "Resource group with name '$($ResourceGroupTest)' does not exist."

    # Create resource group
    New-AzureRmResourceGroup -Name $ResourceGroupTest -Location "West Europe" -Verbose
} else {
    Write-Host "Found Resource group with name '$($ResourceGroupTest)'."
}

Now, when I run this script, I get this sort of output:

Start to check if Resource group 'ResourceGroupForStorageAccount' exists...
Found Resource group with name 'ResourceGroupForStorageAccount'.
Account                      SubscriptionName               Tenant ...
-------                      ----------------               -------- ...
[email protected]            Some subscription              ...             

But I cannot find this newly created resource group with name ResourceGroupForStorageAccount in the list of resource groups in the Azure RM portal.

Where is my problem?

2

There are 2 best solutions below

0
On BEST ANSWER

The value for -ErrorVariable is incorrect, please use NotPresent instead of $NotPresent for the parameter -ErrorVariable. If you use -ErrorVariable $NotPresent, then the $NotPresent is always null/false, so the create resource command never executes.

sample code like below:

#your other code here.

# Check if ResourceGroup exists
Get-AzureRmResourceGroup -Name $ResourceGroupTest -ErrorVariable NotPresent -ErrorAction SilentlyContinue

Write-Host "Start to check if Resource group '$($ResourceGroupTest)' exists..."
if ($NotPresent) {
    Write-Host "Resource group with name '$($ResourceGroupTest)' does not exist."

    # Create resource group
    New-AzureRmResourceGroup -Name $ResourceGroupTest -Location "West Europe" -Verbose
} else {
    Write-Host "Found Resource group with name '$($ResourceGroupTest)'."
}
0
On

just to add to existing answer, this happens because powershell expands variable in your expressions -ErrorVariable $NotPresent. and because your variable doesnt exist it becomes: -ErrorVariable. So it doesnt create a variable called not present and your if() statement doesnt work as you expect it to.