Skip to content

Instantly share code, notes, and snippets.

@lawrencegripper
Last active August 29, 2015 13:56
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 lawrencegripper/7a284e635a964b127118 to your computer and use it in GitHub Desktop.
Save lawrencegripper/7a284e635a964b127118 to your computer and use it in GitHub Desktop.
PowerShell - Cleanup unused Azure Services
$performRemove = $true
#Find all services used by your VMs
$servicesUsedByVms = @{}
$vms = Get-AzureVM
foreach ($v in $vms)
{
$servicesUsedByVms.Add($v.ServiceName, $v)
}
#Find all services without active deployments
$servicesWithoutDeployments = @{}
$services = Get-AzureService
foreach ($s in $services)
{
$response = Get-AzureDeployment -ServiceName $s.ServiceName -ErrorVariable depError -ErrorAction SilentlyContinue | ?{$depError.Count -eq 1}
if ($depError.Count -eq 1 -and $depError.Item(0).Exception.ErrorDetails.Message -eq "No deployments were found.")
{
$servicesWithoutDeployments.Add($s.ServiceName, $s)
}
}
#Pull out Unused services and confirm they're not used by vm. Technically not necessary but being careful
$unusedServices = @{}
foreach ($s in $servicesWithoutDeployments.Keys)
{
if ($servicesUsedByVms.ContainsKey($s))
{
"Contained - VM Paused: " + $s
}
else
{
"Does not Contained paused VM. Marked for Removal: " + $s
$unusedServices.Add($s, $servicesWithoutDeployments.Values[$s])
}
}
#Preform action on that service
foreach ($s in $unusedServices.Keys)
{
if ($performRemove)
{
Start-Job -scriptBlock {
param($s)
Write-host "Performing Remove " + $s -ForegroundColor DarkYellow
Remove-AzureService -ServiceName $s -Force
write-host "Remove Completed" -ForegroundColor DarkYellow
} -ArgumentList $s
}
}
# Wait for it all to complete
While (Get-Job -State "Running")
{
Start-Sleep 10
}
# Getting the information back from the jobs
Get-Job | Receive-Job
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment