Write to MSMQ from Powershell (And View in Server Manager)

First make sure MMSQ is installed, and then for now, manually create your queue using the Server Manager MMC (Microsoft Management Console) GUI (Graphical User Interface). Perhaps in an upcoming blog I will demonstrate the creation of the queue itself in Powershell.

NOTE: MSMQ can only hold messages up to 4MB!

MSMQ_New_PrivateQueue1

Select whether you want your queue to be transactional or not (for help in making this decision, see this link: http://msdn.microsoft.com/en-us/library/ms704006%28v=vs.85%29.aspx
MSMQ_New_PrivateQueue2

Here is the sample code. I have created two functions, one which supports transactional queues, and one non-transactional queues. Note, if I wanted to make the routines more flexible, I could allow the encoding type to be passed as a parameter; the code below assumes UTF8 encoding.

<pre>
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")

function WriteMessageToMSMQTrans($queueName, $message, $label)
  {
     $queue = new-object System.Messaging.MessageQueue $queueName
     $utf8 = new-object System.Text.UTF8Encoding

     $tran = new-object System.Messaging.MessageQueueTransaction
     $tran.Begin()

     $msgBytes = $utf8.GetBytes($message)

     $msgStream = new-object System.IO.MemoryStream
     $msgStream.Write($msgBytes, 0, $msgBytes.Length)

     $msg = new-object System.Messaging.Message
     $msg.BodyStream = $msgStream   
     if ($label -ne $null)
       {
         $msg.Label = $label
       }
     $queue.Send($msg, $tran)

     $tran.Commit()
     Write-Host "Message written"
  }

function WriteMessageToMSMQNonTrans($queueName, $message, $label)
  {
     $queue = new-object System.Messaging.MessageQueue $queueName
     $utf8 = new-object System.Text.UTF8Encoding

     $msgBytes = $utf8.GetBytes($message)

     $msgStream = new-object System.IO.MemoryStream
     $msgStream.Write($msgBytes, 0, $msgBytes.Length)

     $msg = new-object System.Messaging.Message
     $msg.BodyStream = $msgStream
     if ($label -ne $null)
       {
         $msg.Label = $label
       }
     $queue.Send($msg)

    Write-Host "Message written"
  }

#-------------------------
#Test the above functions 
#-------------------------
cls  #clear screen (junk from prior runs) 
$queueName = ".\Private$\nealtest"

$message = "This is my first test message"
WriteMessageToMSMQNonTrans $queueName $message $null

$message = "This is my second test message"
WriteMessageToMSMQNonTrans $queueName $message "MyLabel"

Write-Host "Completed"
</pre>

 

Now we can go view the two messages written to the queue.

MSMQ_in_Server_Manager

 

You can right-click “Properties” on either message.  Below, I’m showing the “General” tab with the date the message was written, then the “Body” tag which shows the hex and text of the message.

 

MSMQ_Properties_Tab_General

 

MSMQ_Properties_Tab_BodyText

 

 

Uncategorized  

Leave a Reply