方案:人们经常在Azure中启动一些资源进行测试,并在测试后让其运行。我想创建一个Powershell脚本来识别很长时间(例如20天)未使用的资源并将其删除。
我试图列出资源,但无法获取时间戳。我有一个etag值,里面有时间,但顺序是随机的。我正在尝试解析。有没有更好的方法可以完成这项任务。
答案 0 :(得分:0)
您可以使用如下脚本:
要生成承载令牌,请遵循以下blog
Connect-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName "<Subscription_Name>"
$Headers=@{
'authorization'="Bearer <bearer_token>"
}
# Get all resources and their changed time
$resources= Invoke-RestMethod -uri 'https://management.azure.com/subscriptions/<subscription_id>/resources?api-version=2018-05-01&$expand=changedTime,createdTime' -method get -Headers $Headers | select-object -Expandproperty value
# Delete all resources which have not been changed since 20 days
foreach ($resource in $resources)
{
$count=0
$time=[datetime]::Parse($resource.changedTime)
$datetime = (Get-Date).AddDays(-20)
$utcDatetime = $datetime.ToUniversalTime()
if ($time -lt $utcDatetime)
{
$resource.id
$time
Write-Output "Deleting resource now"
Remove-AzureRmResource -ResourceId $resource.id
}
}
希望这会有所帮助!