Powershell Invoke-Command会导致不同的结果

问题描述 投票:2回答:2

我有一个用于清除计算机上的消息队列的函数,但我希望调整它并使其更加健壮。即使当前机器没有安装MSMQ,我也希望能够将命令发送到机器。

本地命令没有问题,但是当调用invoke-command时,检查队列是否存在会返回false(即使队列确实存在)。以前有没有人碰到这样的事情?有什么建议?

这是我的功能:

Function Purge-MessageQueue
{
<#
.Synopsis
   Use hostname to purge message queue
.DESCRIPTION
   Checks if MSMQ is locally installed otherwise fire the purge
   command to the machine you are purging
.EXAMPLE
   Purge-MessageQueue -targetMachine $env:computername -queueName 'test'
#>
Param
(
[Parameter(Mandatory=$true)]
    [String]$targetMachine,
[Parameter(Mandatory=$true)]
    [string]$queueName
)
Write-Verbose "Purging $queueName queue on: $targetMachine"
$queueName = "$targetMachine\$queueName"

$error.clear()
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
try {[void][System.Messaging.MessageQueue]::Exists($queueName)}
catch
{
    if ($_.exception.ToString() -like '*Message Queuing has not been installed on this computer.*') 
    {
        #push command to machine
        $RemoteSuccess = Invoke-Command -ComputerName $targetMachine -ScriptBlock { Param($queueName)
            [void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
            If([System.Messaging.MessageQueue]::Exists($queueName)) 
            {
                $queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
                Try{$queue.Purge()}
                Catch{$error}
            }
        } -ArgumentList $queueName
    }
}
If(!$error)
{
    If([System.Messaging.MessageQueue]::Exists($queueName)) 
    {
        $queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
        $queue.Purge()
    }
}
If(!$Error -and !$RemoteSuccess)
{
    Write-Host "$queueName queue on $targetMachine cleared"
}
Else
{
    Write-Warning "Failed locating queue $queueName on $targetMachine" 
}
}

注意:为了确定究竟发生了什么,我在exists语句中使用了write-host,它返回false。传递scriptblock时找不到队列。它正在另一台机器上执行(测试写入成功的文件)。当我跑:

Write-Host "$([System.Messaging.MessageQueue]::Exists($queueName))`n$queueName"
$objqueue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName

我得到错误的,正确的队列名称,以及以下错误:

使用“0”参数调用“Purge”的异常:“队列不存在或者您没有足够的权限来执行操作。” + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:MessageQueueException + PSComputerName:XXXXXX

直接在机器上运行相同的命令可以正常运行。

我还发现其他人试图在serverfault上做类似的事情:https://serverfault.com/questions/399178/how-to-retrieve-names-of-all-private-msmq-queues-efficiently

当我尝试这个:

Invoke-Command -ComputerName $targetMachine -ScriptBlock { Get-MsmqQueue }

我得到以下结果:

找不到指定的机器。 + CategoryInfo:ObjectNotFound:(:) [Get-MsmqQueue],MessageQueueException + FullyQualifiedErrorId:MachineNotFound,Microsoft.Msmq.PowerShell.Commands.GetMSMQQueueCommand

以下命令确实返回数据,但它不允许我发送清除命令:

Invoke-Command -ComputerName $targetMachine -ScriptBlock {Get-WmiObject -class Win32_PerfRawData_MSMQ_MSMQQueue}

我还尝试将内容写入脚本文件,然后调用该文件,该文件在机器上运行时可以正常工作,但不能通过invoke-command调用:

    $filewriter = @"
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
If([System.Messaging.MessageQueue]::Exists('$queueName')) 
{
    `$objqueue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queueName
    Try{`$objqueue.Purge()}
    Catch{`$error}
}
"@
            $session = New-PSSession -ComputerName $targetMachine 
            Invoke-Command -Session $session -ScriptBlock {Param($FileWriter)
                $FileWriter | Out-File "C:\Temp\PurgeQueue.ps1"
            } -ArgumentList $filewriter
            $test = Invoke-Command -Session $session -scriptblock {Pushd "C:\Temp\"
                .\PurgeQueue.ps1}
powershell msmq invoke-command
2个回答
4
投票

我没有找到原因,但我会总结一下我找到的和我的解决方法

简介:通过invoke-command调用msmq命令时,只显示私有队列并可以对其进行操作。

解决方法:我通过在远程计算机上创建计划任务来调用命令创建的脚本,构建一个处理清除队列并向队列添加消息的函数。

Function Push-MSMQRemoteCommand
{
    Param(
        [Parameter(Mandatory=$true)]
        $targetMachine,
        [Parameter(Mandatory=$true)]
        $password,
        [Parameter(Mandatory=$true)]
        $queueName,
        [Switch]$purge,
        $user,
        $message)
    Begin
    {
        If(!$user){$user = "$env:USERDOMAIN\$env:USERNAME"}
        If($purge -and $message.Length -ne 0){Write-Error "Choose to purge or add... not both" -ErrorAction Stop}

        $queuepath = "$targetMachine\$queueName"
        #build commands to push
        If($purge)
        {
            $scriptblock = @"
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
If ([System.Messaging.MessageQueue]::Exists('$queuePath')) {
`$queue = new-object -TypeName System.Messaging.MessageQueue -ArgumentList $queuePath
`$queue.Purge()
}
"@
        }
        ElseIf($message)
        {
            If($message.Length -eq 0){Write-Error "No message provided to add message" -ErrorAction Stop}
            $scriptblock = @"
[void] [Reflection.Assembly]::LoadWithPartialName("System.Messaging")
`$queue = new-object System.Messaging.MessageQueue "$queuepath"
`$utf8 = new-object System.Text.UTF8Encoding

`$msgBytes = `$utf8.GetBytes('$message')

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

`$msg = new-object System.Messaging.Message
`$msg.BodyStream = `$msgStream
`$msg.Label = "RemoteQueueManagerPowershell"
`$queue.Send(`$msg)
"@
        }

        #Push Commands
        Invoke-Command -ComputerName $targetMachine -ScriptBlock {
            Param($user,$password,$scriptblock)
            $scriptblock | Out-file -FilePath "C:\temp\ManageQueue.ps1" -Force
            $action = New-ScheduledTaskAction -execute 'powershell.exe' -Argument '-File "C:\temp\ManageQueue.ps1"'
            #scheudling action to start 2 seconds from now
            $trigger = New-ScheduledTaskTrigger -Once -At ((Get-Date)+(New-TimeSpan -Seconds 2))
            Register-ScheduledTask -TaskName RemoteQueueManager `
                               -Action $action `
                               -Trigger $trigger `
                               -User "$user"`
                               -Password $password
            #Start-Sleep -Seconds 10
            Unregister-ScheduledTask -TaskName RemoteQueueManager -Confirm:$false
            Remove-Item -Path "C:\temp\ManageQueue.ps1" -Force
        } -ArgumentList $user,$password,$scriptblock
    }
}

1
投票

根据你的分析,我觉得这是权利问题。

您是否检查了用户的权利?

如果您是普通用户,则必须在目标计算机/服务器/ VM上执行以下操作(而不是管理员):

1)首先创建一个组并添加用户

net localgroup "Remote PowerShell Session Users" /add
net localgroup "Remote PowerShell Session Users" the-user /add

2)调用GUI

Set-PSSessionConfiguration microsoft.powershell -ShowSecurityDescriptorUI

3)添加Remote PowerShell Session Users组并授予execute (invoke)权利

4)重启服务:

Set-PSSessionConfiguration microsoft.powershell -ShowSecurityDescriptorUI

5)用户现在应该能够运行远程会话

原始来源是here

© www.soinside.com 2019 - 2024. All rights reserved.