我在
C:\Program Files\WindowsPowerShell\Modules\PennoniAppManagement目錄中創建了一個自定義 powershell 模塊。每當我對模塊中的函式進行更改,然后將模塊匯入腳本時,更新的代碼都不會生效。有什么解決辦法嗎?
uj5u.com熱心網友回復:
確保在重新匯入之前從會話中洗掉已加載的模塊版本:
Remove-Module PennoniAppManagement -Force
Import-Module PennoniAppManagement
uj5u.com熱心網友回復:
通常,- 本身 - 足以強制將更新的模塊重新加載到當前會話中。
Import-Module-ForceImport-Module -ForceRemove-Module在重新加載模塊之前隱式執行(如果當前未加載-Force模塊,則正常加載模塊)。另請注意,如果您通過陳述句加載模塊
using module(至少從 PowerShell 7.1.2 開始),則不能強制重新加載模塊。值得注意的using module是,如果模塊匯出class呼叫者應該看到的自定義定義,則需要匯入方法-有關詳細資訊,請參閱此答案。
Mathias 的兩步方法-
Remove-Module -Force,然后是Import-Module- 在某些情況下顯然是需要的,而且您的方法似乎也需要。最好了解何時需要兩步法。Mathias 認為它??與自
class定義定義的快取版本(在模塊內部使用)延遲而不是在Import-Module -Force呼叫時重新加載和重新定義有關。也就是說,雖然整個模塊可能會重新加載,但它可能正在陳舊的狀態 下運行class。至少在下面的簡單場景中,無論是在 Windows PowerShell 5.1 中,還是在 PowerShell (Core) 7.2.1 中,我都無法重現此問題,但可能存在問題確實出現的場景。該
Remove-Module檔案-Force僅將引數描述為與加載模塊的模塊資訊物件上可用的 - 很少使用的 -.AccessMode屬性相關(您可以使用 來檢查它)。默認值為,允許隨時卸載(移除)模塊。如果屬性值為,則需要卸載;如果是,則一旦加載,模塊就根本無法從會話中洗掉 - 至少不能使用.(Get-Module...).AccessModeReadWriteReadOnlyRemove-Module -ForceConstantRemove-Module- 值得注意的是,隱性與發生卸載
Import-Module -Force是沒有受到這些限制,隱含卸載,即使它的一個模塊.AccessMode是Constant(因為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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405503.html
標籤:
下一篇:將陣列中的值放入另一個陣列特定列
