Delete-AzureResource.ps1

<#PSScriptInfo
 
.VERSION 1.0.0.2
 
.GUID ba60be59-a510-4ca2-a15d-34cbb83ed089
 
.AUTHOR maabusha
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI http://mabushaireh.info/posts/about-register-selfdestructiveazresource
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 Automatically cleanup Azure reasource on a specfied schedule
 
#>
 


[CmdletBinding()]
Param(
  [Parameter(Mandatory=$False)]
  [string]$ResourceId,
  [Parameter(Mandatory=$False)]
  [string]$ResourceGroup
)
$VerbosePreference = "continue"

$ScriptVersion = '1.0.0.2'

# Write the script version
Write-Host ("Script version: {0}" -f $ScriptVersion)

# Write the command line that was used when the script was called
Write-Host ("Command line: {0}" -f $MyInvocation.Line)

# Get the current time in UTC
Write-Host ("Current UTC time: {0}" -f [System.DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss'))
# PowerShell code
########################################################
# Log in to Azure with RM (standard code)
########################################################
Write-Verbose -Message 'Connecting to Azure'
 
# Name of the Azure Run As connection
$ConnectionName = 'AzureRunAsConnection'
$errorActionPreference = "Stop" 
try
{
    # Get the connection properties
    $ServicePrincipalConnection = Get-AutomationConnection -Name $ConnectionName       
  
    'Log in to Azure...'
    $null = Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $ServicePrincipalConnection.TenantId `
        -ApplicationId $ServicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint 
}
catch 
{
    if (!$ServicePrincipalConnection)
    {
        # You forgot to turn on 'Create Azure Run As account'
        $ErrorMessage = "Connection $ConnectionName not found."
        throw $ErrorMessage
    }
    else
    {
        # Something else went wrong
        Write-Error -Message $_.Exception.Message
        throw $_.Exception
    }
}
########################################################
 
if ($PSBoundParameters.ContainsKey("ResourceId")) {
    Write-Verbose -Message "Deleting [$ResourceId]"
    Remove-AzureRmResource -ResourceId $ResourceId -Force
}
else {
    Write-Verbose -Message "Deleting Resource Group[$ResourceGroup]"
    Remove-AzureRmResourceGroup -Name $ResourceGroup -Force
}