powershell 无法在脚本中列出 AzResourceGroup 名称

powershell failing to list AzResourceGroup name in script

这个 powershell 的东西很绿色,但我有一个我正在尝试重写的脚本(出于教育目的)需要手动将 AZ 中的资源组输入到一个变量中,然后循环(它删除了所述资源组).

$_names = 'dmz-dev-mgmt', 'dmz-dev-container','dmz-dev-governance', 'dmz-dev-global-dns','dmz-dev-automation','dmz-dev-consumption','dmz-dev-network','NetworkWatcherRG'

我目前有以下内容

az login

Connect-AzAccount -Subscription "DEV Data Platform"

Get-AzResourceGroup |select ResourceGroupName

如果我 运行 这些命令在 powershell 中单独 运行 都很好,如果我 运行 脚本本身在执行 Connect-AzAccount 之后失败 return Get-AzResourceGroup

我希望通过脚本将此列表 return 添加到 $_names 变量

这可能吗?

您可以使用以下方法获取所有资源组名称,然后将其作为变量传递给其他脚本并根据您的要求使用它:

getresources.ps1

function ResourceGroups
{
$rgs=Get-AzResourceGroup 
return $rgs.ResourceGroupName
}
##to display the result if required
foreach ($x in ResourceGroups){
$x
}

deletegroup.ps1

Write-Host ("The acquired list of resource group names is as below:")
. .\getresources.ps1;$_names=ResourceGroups
Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
foreach($_name in $_names){
$delete= az group delete --name $_name
Write-Host "Resource Group $_name Deleted Successfully!!!"
}

注意: 我将两个脚本都保存在一个位置,这就是为什么在第二个脚本中使用这一行 . .\getresources.ps1;$_names=ResourceGroups 如果您将它们保存在不同的位置,那么您必须使用 . .\path\to\script1.ps1;$_names=ResourceGroups

加载它

输出:

完成 az loginconnect-azaccount 我 运行 脚本如下:


单个脚本:

Write-Host ("The acquired list of resource group names is as below:")
$rgs=Get-AzResourceGroup 
$rgs.ResourceGroupName
Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
foreach($_name in $rgs.ResourceGroupName){
$delete= az group delete --name $_name
Write-Host "Resource Group $_name Deleted Successfully!!!"
}