如何为采用单个数组参数的构造函数调用 New-Object? [英] How do I call New-Object for a constructor which takes a single array parameter?

查看:31
本文介绍了如何为采用单个数组参数的构造函数调用 New-Object?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PowerShell 中,我想使用 New-Object 来调用单参数 .Net 构造函数 new X509Certificate2(byte[] byteArray).问题是当我使用来自 powershell 的字节数组执行此操作时,我得到 <块引用>

新对象:找不到X509Certificate2"的重载和参数计数:516".

解决方案

这种使用 new-object 的方法应该有效:

$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate `-ArgumentList @(,$bytes)

诀窍是 PowerShell 需要一个构造函数参数数组.当只有一个参数并且它是一个数组时,它可能会混淆 PowerShell 的重载解析算法.上面的代码通过将字节数组放在一个只有一个元素的数组中来帮助它.

更新: 在 PowerShell >= v5 中,您可以像这样直接调用构造函数:

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate]::new($bytes)

In PowerShell, I want to use New-Object to call a single-argument .Net constructor new X509Certificate2(byte[] byteArray). The problem is when I do this with a byte array from powershell, I get

New-Object : Cannot find an overload for "X509Certificate2" and the argument count: "516".

解决方案

This approach to using new-object should work:

$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate `
      -ArgumentList @(,$bytes)

The trick is that PowerShell is expecting an array of constructor arguments. When there is only one argument and it is an array, it can confuse PowerShell's overload resolution algorithm. The code above helps it out by putting the byte array in an array with just that one element.

Update: in PowerShell >= v5 you can call the constructor directly like so:

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate]::new($bytes)

这篇关于如何为采用单个数组参数的构造函数调用 New-Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆