How do I wait for return for .NET method execution finished?

I have code which read remote MSMQ queue and outputs messages to the screen. Problem is that code continues executing while Stream is being received on the client. How do I make code to wait to finish execution.

[Reflection.Assembly]::LoadWithPartialName("System.Messaging") | out-Null $QueueName = "FormatName:DIRECT=OS:computer1\private$\an" $QueuesFromDotNet = new-object System.Messaging.MessageQueue $QueueName $msg = $QueuesFromDotNet.Peek() line 10: $content = [System.Text.UTF8Encoding]::UTF8.GetString($msg.BodyStream.ToArray()) $content

I want code to wait on line 10 untill BodyStream.ToArray() received entire contents of the message.

PowerShell always waits for a .NET method to finish executing. If you’re getting partial data there, then it’s a flaw in how you’re using those Message / MessageQueue classes. I’m not familiar enough with those to recommend a solution, though.

Hello GS,

The Peek method you are using only obtains the first message in the queue, so this will only output once before the method completes, standard behaviour like Dave says.

That method is unlikely to be unsuitable in any case, since it does not remove the first message from the queue. Even if you do a loop, you will still get the same message back. You’re more likely going to want to use the Receive method, which also removes the item from the message queue.

Maybe you want to try (untested), something like below. It’s likely not be necessary to specify the type before $message, but it’s a habit I’ve gotten into when using .net in PowerShell.

[System.Messaging.Message] $Message =	$QueuesFromDotNet.Receive()
$BodyText = $Message.Body

As a sidenote, why you invoke .NET assemblies? There are a whole bunch of MSMQ cmdlets out there. For example for what you are trying to achieve can be done much simpler with the following code. It does a non-destructive read of the queue:

Get-MsmqMessage -Name 'computer1\private$\an' | Receive-MsmqQueue -Transactional -Peek