Skip to content

Instantly share code, notes, and snippets.


lawrencegripper/Script.ps1 Secret

Last active Aug 29, 2015
What would you like to do?
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
"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 {
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
You can’t perform that action at this time.