How to delete resource groups in parallel

Problem:

I want to delete all the resource groups in Azure in parallel.

Solution:

Use ForEach-Object and Start-Job PowerShell cmdlets.

Get-AzResourceGroup | ForEach-Object { Start-Job -InputObject $_ -ScriptBlock { $Input | Remove-AzResourceGroup -Force } }

Explanation:

I am preparing for a demo and I have created a lot of resource groups in Azure that I no longer need.

When I rehearse I repeat the demo over and over again until I have seen it break in every possible way. The quicker I can clean up the more times I can run the demo to make sure when I am on stage I am ready. Deleting the resource groups from the portal is too many clicks.  If you do not use Start-Job the deletes take forever and are completed one after the other. Using Start-Job, with a single line of PowerShell I can delete all the resource groups in parallel.

Be very careful with this technique because the command above deletes every resource group in your subscription.  You can use a Where-Object to filter the list of resource groups returned and piped to the ForEach-Object.  When building your command I would replace the -Force with -WhatIf to test it out.  You can use the Receive-Job with the ID of the job to see the output you would have seen if run normally. To get the job ids just run Get-Job.

Comments (2) -

  • Mike

    4/10/2019 11:50:57 AM | Reply

    'with great power comes great responsibility'

  • tim kelley

    2/10/2020 7:36:19 PM | Reply

    I got this error.
    ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert the "Get-AzResourceGroup" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
    At line:1 char:123
    + ... $Input | Remove-AzResourceGroup -Force } }Get-AzResourceGroup | ForEa ...
    +                                               ~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (Smile [ForEach-Object], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand

Add comment

Loading