在 Powershell 中找不到 "XmlMessageFormatter" 和参数计数的重载:N

Cannot find an overload for "XmlMessageFormatter" and the argument count: N in Powershell with New-Object

我似乎无法让 Powershell 2.0 中的 New-Object 函数为类型 XmlMessageFormatter.

使用正确的构造函数

XmlMessageFormatter 的 MS 文档在这里: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

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

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

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