【问题标题】:Reload the PowerShell module every time the script is executing每次执行脚本时重新加载 PowerShell 模块
【发布时间】:2022-01-24 16:37:07
【问题描述】:

我在 PowerShell 模块文件中有一个类。 (A.psm1)

class A  {

    [void] printString() {
        write-host 111
    }

}

我还有一个使用该类的简单脚本。

Using module C:\temp\A.psm1

$a = [A]::new()
$a.printString()  # prints 111

但是如果我从类中更改方法,例如,如下所示(将111 替换为222

[void] printString() {
     write-host 222
}

如果我重新启动我的脚本,它仍然会打印111。仅当我重新启动 PowerShell 控制台时,它才会打印新值。 如果我只在控制台中工作,我可以使用Import-Module ... -Force 命令。但它在脚本中不起作用。

那么有没有办法在每次启动脚本时重新加载 PowerShell 模块而无需重新启动控制台本身?

【问题讨论】:

    标签: powershell module reload


    【解决方案1】:

    这种不幸的行为是well-known issueas mklement0 points out目前不存在真正的好的解决方案

    根本原因有点令人费解(行为在 5 年后仍然存在的部分原因),但基本上是以下三方面的冲突:

    • PowerShell 中的模块生命周期管理(模块假定可重新加载)
    • .NET 中的类型定义生命周期管理(在进程的生命周期内永远不能“未定义”类型*)
    • using module 提供自定义类型解析时解析的方式 - 说白了,它并不是一个特别成熟的功能

    虽然不存在好的解决方案,但 VSCode PowerShell 扩展有一个配置选项allowing you to run debug sessions in a temporary shell,使其成为非问题:

    {
      "powershell.debugging.createTemporaryIntegratedConsole": true
    }
    

    设置后,您可以使用以下工作流程进行测试/调试:

    1. 在编辑器中打开脚本
    2. 通过调试器运行它 (Shift+Ctrl+D -> Run and Debug)
    3. 观察printString() 打印111
    4. 修改模块文件,保存
    5. 再次通过调试器运行脚本
    6. 观察printString() 现在打印新值

    【讨论】:

    • 谢谢! VS Code 中的解决方法适合我的需要!
    • @АртурГудиев 很高兴听到,不客气! FWIW 这也是我使用类开发模块的方式:-)
    • 我明白了 :-) 挺方便的。
    【解决方案2】:

    据我所知,没有好的解决方案,不幸的是(从 PowerShell 7.2 开始):using module 语句 - 这是从模块加载 classes 的先决条件 -没有等效于 Import-Module-Force 开关,用于强制重新加载模块。

    解决方法

    # (Force-re)load the module and get a reference to the module.
    # This does NOT give you access to the classes defined in the module.
    $module = Import-Module C:\temp\A.psm1 -PassThru -Force
    
    # Use the module reference to execute code *in the module's* context,
    # where the class *is* defined, so you can obtain a reference to the
    # [A] class (type) this way:
    $classA = & $module { [A] }
    
    $classA::new().printString()
    
    • 如您所见,这需要修改源代码

    • 如果您使用带有 PowerShell 扩展的 Visual Studio Code,则可以避免这种情况,如 Mathias R. Jessen's helpful answer 所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多