Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinyar/8cf737640691ad38947f561d6b7892fe to your computer and use it in GitHub Desktop.
Save vinyar/8cf737640691ad38947f561d6b7892fe to your computer and use it in GitHub Desktop.
Delete Azure resource groups that were created n or more days ago
$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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment