windowspowershellrabbitmq

Powershell script to Purge all RabbitMQ queues for all vhosts


I'm runnings tests thath fills RabbitMQ queues with messages. I have multiple vhosts and each host has multiple queues with lots of messages. I want a Powershell script that will simply purge all messages from all queues for all vhosts. There is already a script for Python that purges all queues for a single vhost, but I want to use powershell and I want to purge all queues for all vhosts.

I don't want to delete the queues or vhosts, I only want to purge the queues of all messages. I'm using RabbitMQ version 3.12.10.

Does anyone have such a script?


Solution

  • I created a powershell script based on the 'rabbitmqctl' documentation. The script will only delete unacked messages. The script uses 3 rabbitmqctl commands:

    1. rabbitmqctl list_vhosts > vhosts.txt Which fetches a list of all vhosts and stores the list to a file.
    2. rabbitmqctl list_queues -p $vhost > queues.txt Which fetches a list of all queues for a given vhost, and stores the queue names to a file.
    3. rabbitmqctl purge_queue -p $vhost $queueName Which purges a given queue for a give vhost.

    Remember to add the RabbitMQ bin dir to you environment Path variable to enable rabbitmqctl in the powershell terminal. The script is filtering out some of the generic progam output, so based on what version of RabbitMQ you are using and you environment, you may have to modify the script to work for you.

    Here's the script:

    rabbitmqctl list_vhosts > vhosts.txt
    foreach($vhost in Get-Content .\vhosts.txt) {
        if ($vhost.StartsWith("Listing vhosts") -or $vhost.StartsWith("name")) {    # skipping the generic program output
            continue;
        }
        Write-Host "Checking vhost $($vhost) for queues"
        rabbitmqctl list_queues -p $vhost > queues.txt
    
        foreach ($queueLine in Get-Content .\queues.txt) {
            if ($queueLine.StartsWith("Timeout: ") -or $queueLine.StartsWith("Listing queues") -or $queueLine.StartsWith("name")) { # skipping the generic program output
                continue;
            }
            $split = $queueLine -split "\s+"    # splitting string on both space and tab
            $queueName = $split[0]
            $messageCount = $split[1]
            if ($messageCount -eq 0 ) {
                continue;
            }
            rabbitmqctl purge_queue -p $vhost $queueName
        }
    }
    Remove-Item "vhosts.txt"
    Remove-Item "queues.txt"