0

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.

Gordon
  • 6,257
  • 6
  • 36
  • 89
  • As an aside: The PowerShell ISE is [obsolescent](https://learn.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [should be avoided going forward](https://stackoverflow.com/a/57134096/45375) (bottom section). – mklement0 Nov 08 '19 at 23:24

2 Answers2

1

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
js2010
  • 23,033
  • 6
  • 64
  • 66
  • I have `[reflection.assembly]::Load('System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')` in the method already. I tried the Using and it doesn't seem to help for me, same error. – Gordon Nov 08 '19 at 21:40
  • Also tried `add-type -AssemblyName system.security` to no effect. Really weird that the cmdlet works, but the constructor barfs. – Gordon Nov 08 '19 at 21:46
0

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)
Jacob Kucinic
  • 115
  • 10
  • 1
    `using namespace` doesn't _load_ types (assemblies), it just makes it more convenient to refer to an already loaded assembly's types by mere type name, without having to specify the namespace part also. Note that the code in the question uses full type names, so your solution won't help. Yes, `[System.Security.Cryptography.Xml]` is available by default in PowerShell _Core_, but it isn't in _Windows PowerShell_. As an aside: `[xml]` is `System.Xml.XmlDocument`, from a different assembly, and it can be referred to as `[xml]` by default in _both_ editions, because it is a _type accelerator_. – mklement0 Nov 08 '19 at 23:49