Last active
August 26, 2022 11:03
-
-
Save rcabr/ff3e2a7b92d12e876bfe5d4fdcf89aa1 to your computer and use it in GitHub Desktop.
Delete Azure resource groups that were created n or more days ago
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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