无法在 Powershell 中使用 Azure 命令删除 Azure Policy 分配

Not able to delete Azure Policy assignment using Azure commands in Powershell

提问人:robtje 提问时间:11/9/2023 更新时间:11/9/2023 访问量:84

问:

我现在在这个问题上卡住了 2 天,但我似乎无法使用 Azure powershell 命令或 az 命令删除策略分配。

所有命令都成功执行,我能够列出所有分配。az delete 命令也会成功执行,但不会删除分配,因为它们仍存在于 Azure 门户策略中。

尝试了以下 Powershell 脚本:

$ResourceGroup = "PoliciesTest"
$query = "assignment"

# List policy assignments and extract the name and id
$assignments = az policy assignment list --resource-group $ResourceGroup --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.name -like "*$query*" }

# Iterate through the assignments and display name and id
foreach ($assignment in $assignments) {
    Write-Host "Name: $($assignment.name)"
    Write-Host "ID: $($assignment.id)"
    Write-Host "--------------------"
    az policy assignment delete --name $assignment.name --scope $assignment.id  --debug

}

执行脚本的结果

Stack overflow 上有一个问题也有同样的问题,但他的问题通过给出范围得到了解决。他的解决方案对我不起作用。

azure powershell azure-policy

评论

0赞 mclayton 11/9/2023
如果在常规的非 powershell 命令提示符下运行该命令,是否会遇到同样的问题?作为测试,尝试移除开关并添加开关 - 这将为您提供更多输出,并且您也许可以在某处找到错误消息以指出问题所在......az--only-show-errors--debug
0赞 robtje 11/9/2023
@mclayton,在CMD中运行删除命令时的行为相同。我让命令使用调试选项运行,但它只是给我返回 204,这通常意味着它成功了,但分配仍在门户中。

答:

0赞 Venkat V 11/9/2023 #1

无法在 Powershell 中使用 Azure 命令删除 Azure Policy 分配

如果在尝试删除分配时收到响应,则门户可能需要一些时间才能将其从显示中删除。若要验证,请运行变量。204Azure Policy$assignments

在运行 PowerShell 代码之前,我在门户中具有以下名称的策略分配。venkat

enter image description here

$scope = "/subscriptions/b83c1ed3-xxxxfjgjgj-b5ba-2bfhn4n5n6n"
$query = "venkat"
$assignments = az policy assignment list --scope $scope --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.displayName -like "*$query*" }

foreach ($assignment in $assignments) {
$name= $assignment.name
Write-Host "Name: $($name)"
$scopeid = $assignment.id
Write-Host "ID: $($scopeid)"
Write-Host "--------------------"
az policy assignment delete --name $name   
}

响应:

enter image description here

运行上述代码后,策略分配已成功从门户中删除。

enter image description here

此脚本将删除策略分配的范围:。Resource group

$scope = "/subscriptions/b83xxxxx-xxxxx-44fb-xxxx-2b83aabcdgfc23f/resourceGroups/venkat"
$query = "allowed"
$assignments = az policy assignment list --scope $scope --output json --only-show-errors | ConvertFrom-Json | Where-Object { $_.displayName -like "*$query*" }
foreach ($assignment in $assignments) {
$name= $assignment.name
Write-Host "Name: $($name)"
$resourcegroup = $assignment.resourceGroup
Write-Host "Resource Group: $($resourcegroup)"
Write-Host "--------------------"
az policy assignment delete --name $name --resource-group $resourcegroup
}

评论

0赞 robtje 11/9/2023
您好 @Venkat V,您的代码用于删除我在订阅级别的分配。在资源组级别,将$scope更改为资源组后,不会删除分配,如下所示:$scope = “/subscriptions/e142501e-XXXX-4cea-9fbd-461a3cf7370a/resourcegroups/PoliciesTest/”。你知道我现在可以执行什么操作吗?
0赞 Venkat V 11/9/2023
嗨,@robtje,我已经使用一个脚本更新了答案,该脚本可以删除资源组的策略分配范围。请查看我更新的答案。
0赞 robtje 11/10/2023
你是神,它现在正在工作!