简体   繁体   中英

New-Object vs [type]::New(), script vs ISE

Sigh. Another day, another PowerShell method interaction with .NET I just don't understand. This time with signed XML, but it's an issue with how to create a new object.

$signedXml = New-Object system.security.cryptography.xml.signedXml -argumentList:$xml works. But where possible I have been moving to [type]::New() . And... $signedXml = [System.Security.Cryptography.Xml.SignedXml]::New($xml) doesn't work. In a script. Works fine in the ISE, but when run as a script I get

Unable to find type [System.Security.Cryptography.Xml.SignedXml].

So, what is going on under the hood such that using a constructor only works in the ISE, while New-Object works in a script also. And, how does one grok what is going to fail? I have plenty of other things I have moved to [type]::New() with no issues. Is my only option to fall back on the commandlet when the constructor fails me? That results in less consistent, readable code in my view.

It didn't work for me in the ISE either, until I did this. Maybe you loaded some module in the ISE that did something like it.

using assembly system.security

Try:

Using namespace System.Security.Cryptography.Xml;

Powershell has the ability to call namespaces like C#.

The below code seemed to work with for me fine in Powershell Core:

Using namespace System.Security.Cryptography.Xml;

$xml = [xml]::New()
$signed = [SignedXml]::New($xml)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM