Write MSMQ Messages from PowerShell

This PowerShell script sends a message to an MSMQ. I did it this particular way because NServiceBus can consume messages sent like this.

[Reflection.Assembly]::LoadWithPartialName(<span class="str">"System.Messaging"</span>);

$queueName = <span class="str">'.\Private$\your.queue.name'</span>;
$queue = <span class="kwrd">new</span>-<span class="kwrd">object</span> System.Messaging.MessageQueue $queueName;
$utf8 = <span class="kwrd">new</span>-<span class="kwrd">object</span> System.Text.UTF8Encoding;

$tran = <span class="kwrd">new</span>-<span class="kwrd">object</span> System.Messaging.MessageQueueTransaction;
$tran.Begin();

$msgContent = <span class="str">'&lt;?xml version="1.0" ?&gt;
    &lt;Messages xmlns="your-xml-namespace"&gt;
        &lt;IWebApplicationStartupCompleting&gt;
        &lt;/IWebApplicationStartupCompleting&gt;
    &lt;/Messages&gt;'</span>;
$msgBytes = $utf8.GetBytes($msgContent);

$msgStream = <span class="kwrd">new</span>-<span class="kwrd">object</span> System.IO.MemoryStream;
$msgStream.Write($msgBytes, 0, $msgBytes.Length);

$msg = <span class="kwrd">new</span>-<span class="kwrd">object</span> System.Messaging.Message;
$msg.BodyStream = $msgStream;
$queue.Send($msg, $tran);

$tran.Commit();
This entry was posted in CodeMinder, MSMQ, PowerShell, Programming. Bookmark the permalink.
  • http://www.schellack.net/jonathan/ Schellack

    I also like to set the message label, so that anyone who looks in a message queue and sees the message will know what it is without having to open it. Simply add .Label = ‘your label'; after the .BodyStream line.

  • http://www.sixgun.co.uk/ Antony Scott

    Excellent post, helped me avoid writing a console app which just dumped a simple message on the bus. Thanks.

    • Jason

      Glad to hear that, Antony – thanks for dropping me a note!