how to export a class in powershell v5 module

后端 未结 10 695
不思量自难忘°
不思量自难忘° 2020-12-08 14:53

I\'ve got a module setup to be like a library for a few other scripts. I can\'t figure out how to get a class declaration into the script scope calling Import-Module

10条回答
  •  天命终不由人
    2020-12-08 15:11

    I've encountered multiple issues regarding PowerShell classes in v5 as well.

    I've decided to use the following workaround for now, as this is perfectly compatible with .net and PowerShell:

    Add-Type -Language CSharp -TypeDefinition @"
    namespace My.Custom.Namespace {
        public class Example
        {
            public string Name { get; set; }
            public System.Management.Automation.PSCredential Credential { get; set; }
            // ...
        }
    }
    "@
    

    The benefit is that you don't need a custom assembly to add a type definition, you can add the class definition inline in your PowerShell scripts or modules.

    Only downside is that you will need to create a new runtime to re-load the class definition after is has been loaded for the first time (just like loading assemblies in a c#/.net domain).

提交回复
热议问题