Tim*_*ith 51 arrays parameters powershell constructor
在PowerShell中,我想用来New-Object调用单参数.Net构造函数new X509Certificate2(byte[] byteArray).问题是,当我使用PowerShell的字节数组执行此操作时,我得到了
New-Object:找不到"X509Certificate2"的重载和参数count:"516".
Kei*_*ill 63
这种使用方法new-object应该有效:
$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate `
-ArgumentList @(,$bytes)
Run Code Online (Sandbox Code Playgroud)
诀窍是PowerShell期待一组构造函数参数.当只有一个参数且它是一个数组时,它可能会混淆PowerShell的重载决策算法.上面的代码通过将字节数组放在只有一个元素的数组中来帮助它.
更新:在PowerShell> = v5中,您可以直接调用构造函数,如下所示:
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate]::new($bytes)
Run Code Online (Sandbox Code Playgroud)
Tim*_*ith 10
令我惊讶的是,我尝试了这个,它似乎有效:
[byte[]] $certPublicBytes = something
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate] $certPublicBytes
return $cert
Run Code Online (Sandbox Code Playgroud)
我还不知道它的作用是什么,所以你的解释性评论是值得赞赏的.:)
(注意:我发现使用方括号类型名称,如上所述,也可能导致其他错误,例如'无法转换值'System.Byte []"键入"System.Security.Cryptography.X509Certificates .X509Certificate".错误:"无法找到请求的对象.'基思推荐的显式新对象方法似乎更好!)