Anders G. Nordby

Lead Software Engineer at Sopra Steria

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
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")

# 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
@'
<html>
<head><title>Content of messages in message queue</title></head>
<body>
<pre><div id="text"></div></pre>
<script>
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;
</script>
</body>
</html>
'@ >> $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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: