在远程计算机上创建私人消息队列

时间:2013-12-03 06:43:44

标签: windows powershell message-queue powershell-remoting

我已经读过,在C#中我们无法在远程计算机上创建专用队列: Cannot create private message queue on remote server

我的问题是:在PowerShell脚本中,我们可以这样做吗?这是我的示例脚本:

echo "Loading System.Messaging..."
[Reflection.Assembly]::LoadWithPartialName( "System.Messaging" )
$msmq = [System.Messaging.MessageQueue]

echo "Create the queue"

$qName = "remoteserver\private$\testqueue"  
if($msmq::Exists($qName))
{
    echo ($qName + " already exists ")           
}
else
{
    echo ($qName + " doesn't exists and now to create ......")      

    $q = $msmq::Create( $qName, $TRUE )     

    echo "Private queues has been created"
}

它说“无效的队列路径名”。我还尝试了一些格式:FormatName:DIRECT=OS:remoteserver\private$\testqueue

结果是一样的。有可能吗?

2 个答案:

答案 0 :(得分:6)

是的,似乎不支持通过System.Messaging API创建远程队列,但一切都不会丢失!使用powershell远程处理(如@abatishchev建议的那样)来创建一个本地队列,它可以正常工作。

我将脚本保存到稍微修改的文件(create-queue.ps1)以设置$queueName = '.\private$\testqueue'。然后我使用invoke-command在远程服务器上运行脚本:

Invoke-Command -ComputerName remoteserver -FilePath .\create-queue.ps1

这假设您已在目标服务器上启用了PowerShell远程处理。您应该在服务器完成后收到输出,以便您能够诊断出任何错误。

如果你必须做很多事情,你当然可以将这一切包装在一个很好的powershell函数中:

function Create-MessageQueue {
    param([string]$QueueName,[string]$ComputerName = ".")

    $script = {
        param($qName)

        [Reflection.Assembly]::LoadWithPartialName('System.Messaging') | out-debug
        $msmq = [System.Messaging.MessageQueue]
        $queuePath = ".\private`$\$qName"  
        if($msmq::Exists($queuePath))
        {
            echo "$queuePath already exists "
        }
        else
        {
            echo "'$queuePath' doesn't exists and now to create ......"
            $msmq::Create($queuePath,$true)     
            echo "Private queue '$queuePath' has been created"
        }
    }

    Invoke-Command -ComputerName $ComputerName -ScriptBlock $script -ArgumentList $QueueName
}

答案 1 :(得分:2)

我从文档中收集了一些内容:

  1. 这与PowerShell无关。您也可以在C#中编写它,但它不起作用。
  2. Exists()的文档指出»Exists(String)方法不支持FormatName前缀。«因此,说明队列名称的替代方法也不起作用。
  3. 双引号字符串中的
  4. $在PowerShell中具有重要意义。它用于内联变量扩展。这里没有任何意义,因为它没有形成有效的变量名(或子表达式),因此保持逐字。但是你应该在这里使用单引号字符串。如果有疑问,只需将字符串转储到管道上即可查看其值。
  5. Create()的文档包含以下有趣的表格:

      

    下表显示了此方法在各种工作组模式下是否可用。

    Workgroup mode                                              Available
    =====================================================================
    Local computer                                              Yes
    Local computer and direct format name                       Yes
    Remote computer                                             No
    Remote computer and direct format name                      No 
    

    这可能意味着它无法用于远程计算机名称。