Created
January 14, 2020 15:39
-
-
Save kasuken/625bdfeb50cf93d95e4bd38c0415ccec to your computer and use it in GitHub Desktop.
An Azure Function PowerShell script to clean all expired resources, all empty resource groups and all expired resource groups
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
$currentUTCtime = (Get-Date).ToUniversalTime() | |
$expiredResources = Search-AzGraph -Query 'where todatetime(tags.expireOn) < now() | project id, name' | |
foreach ($r in $expiredResources) { | |
Write-Host "==> Deleting $($r.name)..."; | |
Remove-AzResource -ResourceId $r.id -Force -WhatIf | |
} | |
$expiredResources = Get-AzResourceGroup; | |
foreach ($resourceGroup in $expiredResources) { | |
$count = (Get-AzResource | Where-Object { $_.ResourceGroupName -match $resourceGroup.ResourceGroupName }).Count; | |
if ($count -eq 0) { | |
Write-Host "==> $($resourceGroup.ResourceGroupName) is empty. Deleting it..."; | |
Remove-AzResourceGroup -Name $resourceGroup.ResourceGroupName -Force -WhatIf | |
} | |
} | |
$expiredResources = Get-AzResourceGroup | Where-Object { $_.Tags.expireOn -and [DateTime] $_.Tags.expireOn -lt $currentUTCtime } | |
Foreach ($resourceGroup in $expiredResources) { | |
Write-Host "==> $($resourceGroup.ResourceGroupName) is expired. Deleting it..." | |
Remove-AzResourceGroup -Name $resourceGroup.ResourceGroupName -Force -WhatIf | |
} | |
# Write an information log with the current time. | |
Write-Host "Azure Cleaner ran at : $currentUTCtime" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment