Forked from rcabr/Remove-OldAzureRmResourceGroups.ps1
Created
December 5, 2019 07:37
-
-
Save vinyar/8cf737640691ad38947f561d6b7892fe 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