Check If Azure Resource Group Exist - Azure Powers

2020-08-09 09:36发布

I'm trying to verify if ResourceGroup exist or not so i thought that following code should return true or false, but it doesn't output anything.

$RSGtest = Find-AzureRmResource | Format-List ResourceGroupName | get-unique
$RSGtest -Match "$myResourceGroupName"

Why am I not getting any output?

4条回答
Evening l夕情丶
2楼-- · 2020-08-09 09:48

try this

$ResourceGroupName = Read-Host "Resource group name"
Find-AzureRmResourceGroup | where {$_.name -EQ $ResourceGroupName}
查看更多
Luminary・发光体
3楼-- · 2020-08-09 09:49

I was also looking for the same thing but there was a additional condition in my scenario.

So I figured it out like this. To get the scenario details follow

$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"
查看更多
男人必须洒脱
4楼-- · 2020-08-09 09:52

I am a PS newbie and I was looking for a solution to this question.

Instead of searching directly on SO I tried to investigate on my own using PS help (to get more experience on PS) and I came up with a working solution. Then I searched SO to see how I compared to experts answers. I guess my solution is less elegant but more compact. I report it here so others can give their opinions:

if (!(Get-AzResourceGroup $rgname -ErrorAction SilentlyContinue))
   { "not found"}
else
   {"found"}

Explanation of my logic: I analyzed the Get-AzResourceGroup output and saw it's either an array with found Resource groups elements or null if no group is found. I chose the not (!) form which is a bit longer but allows to skip the else condition. Most frequently we just need to create the resource group if it doesn't exist and do nothing if it exists already.

查看更多
仙女界的扛把子
5楼-- · 2020-08-09 10:06

Update:

You should use the Get-AzResourceGroup cmdlet from the new cross-plattform AZ PowerShell Module now. :

Get-AzResourceGroup -Name $myResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue

if ($notPresent)
{
    # ResourceGroup doesn't exist
}
else
{
    # ResourceGroup exist
}

Original Answer:

There is a Get-AzureRmResourceGroup cmdlet:

Get-AzureRmResourceGroup -Name $myResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue

if ($notPresent)
{
    # ResourceGroup doesn't exist
}
else
{
    # ResourceGroup exist
}
查看更多
登录 后发表回答