Skip to main content
 首页 » 编程设计

powershell之如何在 PowerShell v5 模块中导出类

2024年11月24日24jirigala

我有一个模块设置,就像其他一些脚本的库一样。我不知道如何将类声明放入脚本范围调用 Import-Module .我试着安排Export-Module-class参数,例如 -function ,但没有 -class可用的。我只需要在每个脚本中声明类吗?
设置:

  • ~\documents\windows\powershell\modules\holidays\
  • 中的假期.psm1
  • 事件脚本调用 import-module holidays
  • Holiday.psm1 中有另一个函数正确返回类对象,但我不知道如何在导入
  • 后从事件脚本创建类的新成员

    下面是这个类的样子:
    Class data_block 
    { 
        $array 
        $rows 
        $cols 
        data_block($a, $r, $c) 
        { 
            $this.array = $a 
            $this.rows = $r 
            $this.cols = $c 
        } 
    } 
    

    请您参考如下方法:

    你几乎不能。根据 about_Classes帮助:

    Class keyword

    Defines a new class. This is a true .NET Framework type. Class members are public, but only public within the module scope. You can't refer to the type name as a string (for example, New-Object doesn't work), and in this release, you can't use a type literal (for example, [MyClass]) outside the script/module file in which the class is defined.


    这意味着,如果你想给自己一个 data_block实例化或使用操作这些类的函数,创建一个函数,例如 New-DataBlock并使其返回一个新的 data_block实例,然后您可以使用它来获取类方法和属性(可能包括静态的)。