Created
September 7, 2020 16:54
-
-
Save dzsquared/41256da60a3fd91ab73f843808662fcc to your computer and use it in GitHub Desktop.
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
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