views:

343

answers:

3

I'd like to provide a queuepath and get the number of messages thereupon. Any advice on how this could be done?

A: 

There are a set of MSMQ management cmdlets in the PowerShell Community Extensions. Give these a try and see if any of them help (probably Get-MSMQueue):

Clear-MSMQueue
Get-MSMQueue
New-MSMQueue
Receive-MSMQueue
Send-MSMQueue
Test-MSMQueue

Note: Try grabbing the beta 2.0 module-based distrubtion - just remember to "unblock" the zip before unzipping it.

Keith Hill
A: 

So, I saw this: http://stackoverflow.com/questions/742262/what-can-i-do-with-c-and-powershell and went here:http://jopinblog.wordpress.com/2008/03/12/counting-messages-in-an-msmq-messagequeue-from-c/

And made this

[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
$qsource = @"
public class QueueSizer
    {
        public static System.Messaging.Message PeekWithoutTimeout(System.Messaging.MessageQueue q, System.Messaging.Cursor cursor, System.Messaging.PeekAction action)
        {
            System.Messaging.Message ret = null;
            try
            {
                ret = q.Peek(new System.TimeSpan(1), cursor, action);
            }
            catch (System.Messaging.MessageQueueException mqe)
            {
                if (!mqe.Message.ToLower().Contains("timeout"))
                {
                    throw;
                }
            }
            return ret;
        }

        public static int GetMessageCount(string queuepath)
        {
            System.Messaging.MessageQueue q = new System.Messaging.MessageQueue(queuepath);
            int count = 0;
            System.Messaging.Cursor cursor = q.CreateCursor();
            System.Messaging.Message m = PeekWithoutTimeout(q, cursor, System.Messaging.PeekAction.Current);
            if (m != null)
            {
                count = 1;
                while ((m = PeekWithoutTimeout(q, cursor, System.Messaging.PeekAction.Next)) != null)
                {
                    count++;
                }
            }
            return count;
        }
    }
"@

Add-Type -TypeDefinition $qsource -ReferencedAssemblies C:\Windows\assembly\GAC_MSIL\System.Messaging\2.0.0.0__b03f5f7f11d50a3a\System.Messaging.dll
QueueSizer::GetMessageCount('mymachine\private$\myqueue');

And it worked.

Irwin
A: 

The solution provided by Irwin is less than idea.

There is a .GetAllMessages call you can make to have this done in one check, instead of a foreach loop.

$QueueName = "MycomputerName\MyQueueName" 
$QueuesFromDotNet =  new-object System.Messaging.MessageQueue $QueueName


If($QueuesFromDotNet.GetAllMessages().Length -gt $Curr)
{
    //Do Something
}

The .Length gives you the number of messages in the given queue.

Clarence Klopfstein