Anders G. Nordby

Lead Software Engineer at Sopra Steria

Monthly Archives: October 2018

Reading the Contents of a Private MSMQ with PowerShell

In my current project, we’re using MSMQ for communication between various parts of the system, with the individual messages being in JSON format. For testing purposes, it’s very handy to list out the contents of my private MSMQ queue in a readable format. So I wrote this quick script to help me do just that.

# Set the name of your private queue here
$myQueueName = "my-private-queue"

# Load the messaging assembly

# Location for the temp file
$outputfilename = "C:\temp\$myQueueName.html"

# Getting the messages from the queue
$queueName = ".\Private$\$myQueueName";
$queue = new-object System.Messaging.MessageQueue $queueName;
$utf8 = new-object System.Text.UTF8Encoding;
$msgs = $queue.GetAllMessages();

# Concatening the body of the messages into a JSON array
$messages = $msgs | %{ $utf8.GetString($_.BodyStream.ToArray()) }
$result = $messages -join ", "

# Write the beginning of the HTML file
<head><title>Content of messages in message queue</title></head>
<pre><div id="text"></div></pre>
var json = 
'@ > $outputfilename

# Writing the JSON to the temp file
"[$result]" >> $outputfilename

# Write the rest of the HTML file
var str = JSON.stringify(json, null, 2);
document.getElementById("text").innerHTML = str;
'@ >> $outputfilename

# Opening the file in the Chrome browser
Start-Process $outputfilename

This writes the contents of the queue to a temp file, wrapped in a bit of HTML (using JavaScript for prettyprinting), and opens it with the browser.