问题
I've written the following variations of a function to return a System.Messaging.MessageQueue
object:
set-strictmode -version latest
add-type -AssemblyName System.Messaging
$VerbosePreference = 'Continue'
$DebugPreference = 'Continue'
function Get-MsmqQueue1 {
New-Object "Messaging.MessageQueue" -Args '.\private$\barneytest'
}
function Get-MsmqQueue2 {
$q = New-Object "Messaging.MessageQueue" -Args '.\private$\barneytest'
$q
}
function Get-MsmqQueue3 {
$q = New-Object "Messaging.MessageQueue" -Args '.\private$\barneytest'
Write-Output $q
}
function Get-MsmqQueue3a {
$q = New-Object "Messaging.MessageQueue" -Args '.\private$\barneytest'
if ($q) {
Write-Debug "Successfully created $($q.QueueName)"
} else {
Write-Error "No queue object created"
}
Write-Output $q
}
$q = Get-MsmqQueue3a
$q
if ($q) {
Write-Debug $q.QueueName
} else {
Write-Error "No queue object returned"
}
None of them return an object. It's somehow being swallowed up by PowerShell. Note that the "3a" version has logging to prove that the value it's writing to the pipeline is not null, yet no value is returned from the function.
How can this be? Is this a PowerShell bug?
Many thanks in advance.
回答1:
I'm an idiot. It's not a bug, but it's interesting. Because System.Messaging.MessageQueue
implements System.Collections.IEnumerable
by enumerating it's messages, the behaviour I was seeing was that PowerShell was actually reading the messages off the newly-created queues and putting them into the pipeline rather than the queue objects themselves. Of course because the queues were new, they were empty, so there was nothing passed on down the pipeline.
I just spent most of this afternoon and some hours this evening working this out. I am not proud of myself.
来源:https://stackoverflow.com/questions/15950141/why-cant-a-powershell-function-return-a-messagequeue-object