在 PowerShell 中访问和管理 MSMQ(Microsoft Message Queuing)

在 PowerShell 中访问和管理 MSMQ(Microsoft Message Queuing),可以通过MSMQ 的 PowerShell 模块或 **.NET 类 ** 来实现。以下是详细的操作指南:

$queueName = "private$\test"
$remoteQueuePath = "FormatName:DIRECT=TCP:192.168.8.222\$queueName"
Add-Type -AssemblyName System.Messaging
$queue = New-Object System.Messaging.MessageQueue($remoteQueuePath)
$messageBody = "这是一条发送到远程队列的消息"
$queue.Send($messageBody, "消息标题") # 第二个参数为消息标签(可选)

 


【构造远程队列路径】
# 远程主机名或 IP(替换为实际值)
$remoteServer = "RemoteServer01"

#--------------------------------------
# 队列名称(私有队列需加 private$)
$queueName = "private$\test"


# 构建直接格式名(使用 OS 协议,依赖 Windows 身份验证)
$remoteQueuePath = "FormatName:DIRECT=OS:$remoteServer\$queueName"


#-------------------------------------------------
# 若跨域或 OS 协议失败,可尝试 TCP 协议(需指定远程主机 IP)
$remoteQueuePath = "FormatName:DIRECT=TCP:192.168.8.222\$queueName"

 

【检查队列是否存在】
#--------------------------------------------------
# 加载 System.Messaging 类库(依赖 .NET Framework)
Add-Type -AssemblyName System.Messaging

# 检查远程队列是否存在
$queueExists = [System.Messaging.MessageQueue]::Exists($remoteQueuePath)
if (-not $queueExists) {
Write-Error "远程队列不存在:$remoteQueuePath"
exit
}


【发送消息到远程队列】-------------------------------------

-------------------------------------------------------
# 创建队列对象
$queue = New-Object System.Messaging.MessageQueue($remoteQueuePath)

# 发送文本消息(默认编码为 Unicode)
$messageBody = "这是一条发送到远程队列的消息"
$queue.Send($messageBody, "消息标题") # 第二个参数为消息标签(可选)

 

 

# 发送复杂对象(需序列化,例如 XML 格式)
$complexData = @{
ID = 1001
Name = "测试数据"
Time = Get-Date
}
$xmlBody = [System.Management.Automation.PSSerializer]::Serialize($complexData)
$queue.Send($xmlBody, "复杂对象消息")

Write-Host "消息发送成功!"

posted @ 2025-11-19 13:57  无聊的蚂蚁  阅读(0)  评论(0)    收藏  举报