Skip to content

Instantly share code, notes, and snippets.

@dzsquared
Created September 7, 2020 16:54
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 dzsquared/41256da60a3fd91ab73f843808662fcc to your computer and use it in GitHub Desktop.
Save dzsquared/41256da60a3fd91ab73f843808662fcc to your computer and use it in GitHub Desktop.
workflow ResourceCleaner
{
Param
(
[Parameter(Mandatory=$true)]
[String]
$TargetTagName,
[Parameter(Mandatory=$true)]
[String]
$SubscriptionName
)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Connect-AzAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch
{
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
if($SubscriptionName)
{
try
{
$Subscriptions = Get-AzSubscription -SubscriptionName $SubscriptionName
}
catch
{
$ErrorMessage = "Subscription $SubscriptionName not found."
throw $ErrorMessage
}
}
Set-AzContext -Subscription $SubscriptionName
$GetDateMMddyyyy = Get-Date -Format "MM/dd/yyyy"
"Removing resources for $GetDateMMddyyyy"
$ResourcesToRemove = Get-AzResource -TagName $TargetTagName -TagValue $GetDateMMddyyyy
$ResourcesToRemove | ForEach-Object {
$ResourceName = $_.Name
"Removing $ResourceName"
Remove-AzResource -ResourceId $_.ResourceId -Force
}
$RemoveTrue = "true"
"Removing marked resources"
$ResourcesToRemove = Get-AzResource -TagName $TargetTagName -TagValue $RemoveTrue
$ResourcesToRemove | ForEach-Object {
$ResourceName = $_.Name
"Removing $ResourceName"
Remove-AzResource -ResourceId $_.ResourceId -Force
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment