意图:了解第一次创建资源组的时间。客户端组织希望报告资源组创建时间戳并对其执行操作。这将用于自动化脚本。
不幸的是,资源组上没有创建时间戳属性。使用Get-AzureRmResourceGroup
返回如下对象:
ResourceGroupName : eastus2-something-rg
Location : eastus2
ProvisioningState : Succeeded
Tags :
ResourceId : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/eastus2-something-rg
此功能有been requested,但似乎没有多少票。
如何检索资源组的创建时间戳?
答案 0 :(得分:4)
实际上,资源组没有创建时间戳。
但管理操作记录在日志中,可以使用Get-AzureRmLog
命令检索这些日志。
这是一个PowerShell语句,它遍历订阅的资源组,并查找在n天或更多天前创建的那些(来自this gist):
$days = 7
$pointInTime = [DateTime]::Now.AddDays(-$days);
$horizon = $pointInTime.AddDays(-$days);
"===Removing resource groups created between $horizon and $pointInTime==="
# Get potential log entries
$logs = @()
$logs += Get-AzureRmLog -StartTime $horizon -EndTime $pointInTime -Status "Succeeded" -ResourceProvider "Microsoft.Resources" -WarningAction "SilentlyContinue" `
| Select-Object ResourceGroupName, ResourceId, @{Name="EventNameValue"; Expression={$_.EventName.Value}}, @{Name="OperationNameValue"; Expression={$_.OperationName.Value}}, EventTimestamp, @{Name="HttpVerb"; Expression={$_.HttpRequest.Method}} `
| Where-Object -FilterScript {$_.EventNameValue -EQ "EndRequest" -and $_.OperationNameValue -eq "Microsoft.Resources/subscriptions/resourcegroups/write" -and $_.HttpVerb -eq "PUT"} `
| Select-Object -ExpandProperty ResourceGroupName -Unique
"Expired resource groups (created BEFORE $pointInTime) -> $logs"
# Get recent log entries to remove from the list
$nologs = @()
$nologs += Get-AzureRmLog -StartTime $pointInTime -Status "Succeeded" -ResourceProvider "Microsoft.Resources" -WarningAction "SilentlyContinue" `
| Select-Object ResourceGroupName, ResourceId, @{Name="EventNameValue"; Expression={$_.EventName.Value}}, @{Name="OperationNameValue"; Expression={$_.OperationName.Value}}, EventTimestamp, @{Name="HttpVerb"; Expression={$_.HttpRequest.Method}} `
| Where-Object -FilterScript {$_.EventNameValue -EQ "EndRequest" -and $_.OperationNameValue -eq "Microsoft.Resources/subscriptions/resourcegroups/write" -and $_.HttpVerb -eq "PUT"} `
| Select-Object -ExpandProperty ResourceGroupName -Unique
"Resource groups created AFTER $pointInTime -> $nologs"
# remove any that were found to have recent creation
$rgs = $logs | Where-Object {$nologs -notcontains $_} | Select-Object @{Name="ResourceGroupName"; Expression={$_}} | Get-AzureRmResourceGroup -ErrorAction "SilentlyContinue"
"Existing resource groups to delete -> $($rgs | Select-Object -ExpandProperty ResourceGroupName)"
$rgs | Remove-AzureRmResourceGroup -Force -AsJob
它返回正在运行的作业列表,用于删除资源组(它们可能需要一些时间,具体取决于其内容)。
答案 1 :(得分:0)
此信息可通过ARM获得,但是您必须直接调用API,而不是PS Get-AzureRmResourceGroup(或Get-AzResourceGroup)cmdlet。
请参见Deleting all resources in an Azure Resource Group with age more than x days
本质上,您需要将$ expand = createdTime添加到查询参数,即:
GET https://management.azure.com/subscriptions/1237f4d2-3dce-4b96-ad95-677f764e7123/resourcegroups?api-version=2019-08-01&%24expand=createdTime