首页 > 解决方案 > 找不到“XmlMessageFormatter”的重载和参数计数:Powershell 中的 N 和 New-Object

问题描述

我似乎无法让New-ObjectPowershell 2.0 中的函数为 type 使用正确的构造函数XmlMessageFormatter

MS 文档在XmlMessageFormatter这里:https ://docs.microsoft.com/en-us/dotnet/api/system.messaging.xmlmessageformatter.-ctor?view=netframework-4.8# System_Messaging_XmlMessageFormatter__ctor_System_Type__

我想使用带有类型数组的构造函数:

XmlMessageFormatter(Type[] targetTypes);

我的 powershell 脚本如下所示:

[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging")
$queue = New-Object System.Messaging.MessageQueue $queuePath
[Type[]]$types = [MyNamespace.MyClass1], [MyNamespace.MyClass2], [MyNamespace.MyClass3]
$queue.Formatter = New-Object System.Messaging.XmlMessageFormatter($types);

要重新创建问题,您可能可以使用以下代码:

[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging")
[Type[]]$types = [System.String], [System.Int], [System.Messaging.MessageQueue]
$formatter = New-Object System.Messaging.XmlMessageFormatter($types);

我在这里阅读有关 PowerShell 中的数组:https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7

错误消息似乎认为我正在发送多个参数而不是数组的单个参数:

New-Object : Cannot find an overload for "XmlMessageFormatter" and the argument count: "3".
At C:\temp\test.ps1:20 char:20
+ $queue.Formatter = New-Object System.Messaging.XmlMessageFormatter($types);
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

标签: powershellpowershell-2.0

解决方案


PowerShell 假定您向它传递了一个包含 3 个单独参数参数XmlMessageFormatter构造函数数组,因此... with the argument count: "3".是错误消息的一部分。

使用,一元数组运算符将数组包装$types在另一个数组中,以便 PowerShell$types在调用构造函数时将其视为单个参数参数:

New-Object System.Messaging.XmlMessageFormatter (,$types)

推荐阅读