【问题标题】:Classes loaded as dependency in imported module are not imported into script在导入模块中作为依赖项加载的类不会导入脚本
【发布时间】:2021-04-23 16:54:07
【问题描述】:

我有一些看起来像这样的 PowerShell 模块和脚本:

MyClassModule.psm1

class MyClass {
  #...
}

MyUtilityModule.psm1

using module MyClassModule

# Some code here

MyScript.ps1

using module MyUtilityModule

[MyClass]::new()

我的问题是:

如果将类作为依赖项导入 MyUtilityModule 中,为什么此脚本会失败?

导入是否总是只在它们被导入的直接脚本本地?

有没有办法让它们在 using 语句中全局化?

如果有任何不同,我需要至少向后兼容 PowerShell 5.1 版

【问题讨论】:

    标签: powershell class module using


    【解决方案1】:

    这都是关于范围的。用户体验直接受加载类的方式影响。我们有两种方法:

    1. 导入模块

      是允许将模块内容加载到会话中的命令。

      ... 它必须在您要调用的位于该特定模块中的函数之前调用。但不是必须在您的开头/顶部 脚本。

    2. 使用模块

      ...

      using 语句必须位于脚本的最顶部。它也必须是脚本的第一条语句(cmets 除外)。这 使“有条件地”加载模块成为不可能。

    命令类型,可在脚本、内部函数、公共函数、枚举、类中任意调用

    导入模块,是,否,是,否,否

    使用模块,不,不,是,是,是

    有关详细信息,请参阅这些参考资料

    如何使用类编写 Powershell 模块 https://stephanevg.github.io/powershell/class/module/DATA-How-To-Write-powershell-Modules-with-classes

    您所说的 PowerShell 中的这个模块作用域是什么? https://mikefrobbins.com/2017/06/08/what-is-this-module-scope-in-powershell-that-you-speak-of

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      相关资源
      最近更新 更多