使用PowerShell锁定Azure资源

zxlwwiss  于 2022-12-24  发布在  Shell
关注(0)|答案(1)|浏览(140)

我尝试运行脚本在Azure资源上创建锁,以防止资源被无意中删除。我收到一条错误消息,我不知道为什么它向我显示此错误消息。
脚本:

#Sign in to Azure account
Login-AzAccount

#Select the subscription you want to work on
Select-AzSubscription -Subscription "test.subscription"

#Get All Resources in a resource group
$Resources = Get-AzResource -ResourceGroupName dummy_rg | Format-Table

# Create lock "delete" on each Resource if it doesn't exist
foreach($Resource in $Resources) {

    $ResourceName = $Resource.Name
    $lck = Get-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType
    
    if ($null -eq $lck)
    {
    Write-Host "$ResourceName has no lock"
    
    New-AzResourceLock -resourceGroupName $rg -ResourceName $ResourceName -ResourceType $Resource.ResourceType -LockName "$ResourceName-lck" -LockLevel CanNotDelete -Force
    
    Write-Host "$ResourceName has been locked"
    
    }
    else 
    {
    Write-host "$ResourceName already locked"
    }
    
    }

错误信息:

Gaurav请求结果:

olmpazwi

olmpazwi1#

#Start logging
Start-Transcript -Path "C:\Windows\Logs\Lock - $(((get-date).ToUniversalTime()).ToString("yyyy-MM-dd_hh-mm-ss")).log" -Force

#Connect to Azure account
Login-AzAccount

#Select Azure subscription
Set-AzContext -Subscription "subscription_id_numbers"
#Deny rule on Azure Data Factory and Azure Machine Learning
$Resources = Get-AzResource | Where-Object {$_.Name -NotLike '*adf*' -and $_.Name -NotLike '*aml*'}

# Create lock "delete" on each Resource if it doesn't exist

foreach($Resource in $Resources) {

$ResourceName = $Resource.Name
$lck = Get-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType

if ($lck -eq $null)
{
Write-Host "$ResourceName has no lock"

Set-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType -LockName "$ResourceName-lck" -LockLevel CanNotDelete -Force

Write-Host "$ResourceName has been locked"

}
else 
{
Write-host "$ResourceName already locked"
}

}

#Stop Logging
Stop-Transcript

相关问题