我有一个用于清除计算机上的消息队列的函数,但我希望对其进行调整并使其更加健壮。即使当前机器没有安装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}
答案 0 :(得分: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 :(得分: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。