剧透:我是Azure和Azure Powershell的新手。
我开始学习Azure和Azure Powershell,而我目前的自我锻炼是编写脚本,该脚本检查Azure中是否存在指定的资源组。如果此特定资源组不存在,则创建一个。所以我开始写这个脚本:
# 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)'."
}
现在,当我运行此脚本时,会得到以下输出:
Start to check if Resource group 'ResourceGroupForStorageAccount' exists...
Found Resource group with name 'ResourceGroupForStorageAccount'.
Account SubscriptionName Tenant ...
------- ---------------- -------- ...
my.email@host.com Some subscription ...
但是在Azure RM门户的资源组列表中找不到名为 ResourceGroupForStorageAccount 的新创建的资源组。
我的问题在哪里?
答案 0 :(得分:2)
-ErrorVariable
的值不正确,请为参数NotPresent
使用$NotPresent
而不是-ErrorVariable
。如果您使用-ErrorVariable $NotPresent
,则$NotPresent
始终为null / false,因此create resource命令将永远不会执行。
示例代码如下:
#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)'."
}
答案 1 :(得分:1)
仅是添加到现有答案中,这是因为powershell在表达式-ErrorVariable $NotPresent
中扩展了变量。并且因为您的变量不存在,它变为:-ErrorVariable
。因此,它不会创建一个名为“不存在”的变量,并且您的if()
语句无法按您期望的那样工作。