Why can't a PowerShell function return a MessageQueue object?

筅森魡賤 提交于 2019-12-24 13:33:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!