apr 5 blog

PowerShell and MSMQ – Copy messages between Transactional MSMQ queues

The script below makes it possible to copy messages to Transactional MSMQ queues:



#Setting parameters from prompt
param(
 [string]$vQueueSourceName,
  [string]$vQueueDestinationName
 )

 #Source Queue
 if ( [System.String]::IsNullOrEmpty($vQueueSourceName) )
 {
  write-host "You must provide a source queue name, format like: '.private$sourceQueue'"
  exit
 }

 #Destination Queue
 if ( [System.String]::IsNullOrEmpty($vQueueDestinationName) )
 {
  write-host "You must provide a destination queue name, format like: '.private$sourceQueue'"
  exit
 }

#Set Up Queues
write-host
write-host "MSMQ Source:" $vQueueSourceName
write-host "MSMQ Destination:" $vQueueDestinationName
write-host

$qSource = new-object System.Messaging.MessageQueue $vQueueSourceName
$qDestination = new-object System.Messaging.MessageQueue $vQueueDestinationName
$qSourceMessageCount =  $qSource.GetAllMessages().Length

Write-Host ("COUNT IN SOURCE QUEUE " + $qSourceMessageCount) "MESSAGES";
write-host
$vTotalCountInMSMQ = $qSource.GetAllMessages()
$i = 1

foreach ($msg in $vTotalCountInMSMQ)
{

 #write-host $msg.label #Enable if you want to see the message label
 #write-host $msg.id #_Enable if you want to see the message ID GUID

 Write-Host $i
 $i = $i +1

 #Read Message
  $msg.BodyStream.Position = 0
  $sr = new-object System.IO.StreamReader( $msg.BodyStream )

  #$sr.ReadToEnd() #Enable if you want to see each the message

  $msgBody = $sr.ReadToEnd()

 #Write Message to Destination MSMQ

  $queueName = $vQueueDestinationName
  $msgLabel = $msg.label

  $queue = new-object System.Messaging.MessageQueue $queueName;
  $utf8 = new-object System.Text.UTF8Encoding;

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

  $msgContent = $msgBody;
  $msgBytes = $utf8.GetBytes($msgContent);

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

  $msg = new-object System.Messaging.Message;
  $msg.BodyStream = $msgStream;
  $msg.Label = $msgLabel;
  $queue.Send($msg, $tran);

  $tran.Commit();

 write-host

 if ( $i -eq $qSourceMessageCount +1)
  {
  write-host
  exit
  }
 else
  {
  #$input = read-host -prompt "Press enter for the next message, q to quit"
  write-host
   if ( $input -eq "q" )
   {
    write-host
    exit
   }
  }
}

write-host
Write-Host ("Message copy is done");
Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+