2

I have the following code:

using namespace System.Xml.Linq
using assembly System.Xml.Linq

class error {
    <#
        .PARAMETER type
        The type of the error.
    #>
    [string] $type

    <#
        .PARAMETER message
        The error message.
    #>
    [string] $message

    error() {}

    [XElement] ToXElement() {

        $el = New-Object XElement([XName] "error")
        $attrType = New-Object XAttribute([XName] "type"), $this.type
        $el.Add($attrType)
        $elDesc = New-Object XElement([XName] "desc"), $this.message
        $el.Add($elDesc)

        return $el
    }
}

When I try to import the module using using module error.psm1, PowerShell console would say Unable to find type [XElement] and [XName]. I've tried both absolute and relative class names but still to no avail.

Is there a way I can using the module without having to run Add-Type before I run the script that uses the module?

Environment $PSVersionTable:

PS D:\DiscoveryRunner> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14409.1012
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1012
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Note: A workaround I found is by adding the Add-Type statement in the PowerShell profile (see this docs for more information) however it's an ugly fix and something I want to avoid if possible.

tyteen4a03
  • 1,812
  • 24
  • 45
  • I'd expect you to have to load the assembly before declaring the `using namespace` - have you tried swapping them around? – Mathias R. Jessen Nov 03 '17 at 14:03
  • @MathiasR.Jessen I've tried all combinations of `namespace` and/or `assembly` ordering; none works. – tyteen4a03 Nov 03 '17 at 14:05
  • 1
    @tyteen4a03 `using assembly` do not cause parse time assembly loading. Assembly loading can cause arbitrary code to be executed, which can be undesired. And extracting types from assembly metadata without loading it not yet implemented, AFAIK. – user4003407 Nov 03 '17 at 15:55

0 Answers0