我创建了一个自定义 powershell .psm1 模块,但它在编辑后不会更新

I created a custom powershell .psm1 module but it won't update after an edit

我在
中创建了一个自定义 powershell 模块 C:\Program Files\WindowsPowerShell\Modules\PennoniAppManagement 目录。每当我更改模块中的函数,然后将模块导入脚本时,更新的代码都不会生效。有什么解决办法吗?

确保在重新导入之前从会话中删除已加载的模块版本:

Remove-Module PennoniAppManagement -Force
Import-Module PennoniAppManagement
  • 通常, Import-Module-Force - 就其本身而言 - 足以 force 将更新的模块重新加载到当前会话中。

    • Import-Module -Force 隐式 在重新加载模块之前执行 Remove-Module(如果模块当前未加载,-Force 只是正常加载模块)。

    • 另请注意,如果您通过 using module 加载模块,强制重新加载模块 不是 一个选项statement(至少从 PowerShell 7.1.2 开始)。值得注意的是,如果模块导出调用者应该看到的自定义 class 定义,则需要 using module 导入方法 - 有关详细信息,请参阅

  • - Remove-Module -Force,后跟 Import-Module - 在 某些 情况下显然需要,并且似乎需要在你的。

    • 最好理解什么时候需要两步法。 Mathias 认为它​​与 自定义 class 定义的缓存版本(在模块内部使用)延迟 而不是在调用 Import-Module -Force 时重新加载和重新定义有关。也就是说,虽然整个模块可能会重新加载,但它可能正在 staleclasses 上运行。至少在下面的简单场景中,我 not 无法重现此问题,无论是在 Windows PowerShell 5.1 还是 PowerShell (Core) 7.2.1 中,但可能存在出现问题的场景。

    • Remove-Module documentation describes the -Force parameter solely as relating to the - rarely used - .AccessMode property available on a loaded module's module-information object (you can inspect it with (Get-Module ...).AccessMode)。默认值为ReadWrite,允许随时卸载(移除)模块。如果属性值为ReadOnly,则需要Remove-Module -Force卸载;如果是 Constant,模块一旦加载就根本无法从会话中删除 - 至少不能 with Remove-Module.

      • 值得注意的是,隐式 卸载Import-Module -Force 不受 的约束,甚至隐式卸载模块如果它的 .AccessModeConstant(从 PowerShell 7.1.2 开始;我不清楚这是否是设计使然)。

测试代码,涉及重新加载具有修改后的class定义的模块,以查看Import-Module -Force是否是足够了:

# Create a template for the content of a sample script module.
# Note: The doubled { and } are needed for use of the string with
#       with the -f operator later.
$moduleContent = @'
class MyClass {{
  [string] $Foo{0}
}}

function Get-Foo {{
  # Print the property names of custom class [MyClass]
  [MyClass]::new().psobject.Properties.Name
}}
'@

# Create the module with property name .Foo1 in the [MyClass] class.
$moduleContent -f 1  > .\Foo.psm1

# Import the module and call Get-Foo to echo the property name.
Import-Module .\Foo.psm1; Get-Foo

# Now update the module on disk by changing the property name
# to .Foo2
$moduleContent -f 2  > .\Foo.psm1

# Force-import (reload) the module and 
# see if the property name changed.
Import-Module -Force .\Foo.psm1; Get-Foo

# Clean up.
Remove-Item .\Foo.psm1

Windows PowerShell(最新和最后一个版本是v5.1)和PowerShell (Core) 7.2.1(截至撰写本文时为当前版本),如预期的那样,上述产量为:

Foo1  # Original import.
Foo2  # After modifying the class and force-reloading