首页 > 解决方案 > 如何在不删除以前从模块中导入的其他函数的情况下从模块中强制导入函数?

问题描述

在 PowerShell 模块(parent)中,我想从另一个 PowerShell 模块(child)强制导入一个函数,而不删除以前从子模块(可能由其他父模块)导入的其他函数。

复制:

# childmod.psm1 source

function Write-Foo {
    Write-Host "Foo"
}

function Write-Bar {
    Write-Host "Bar"
}

Export-ModuleMember -Function *
# interactive PS1 session

Import-Module "./childmod.psm1" -Function "Write-Foo" -Force

# This confirms "Write-Foo" function is available.
Get-Command -Module "childmod"

# This will remove the "Write-Foo" function!
Import-Module "./childmod.psm1" -Function "Write-Bar" -Force

# This confirms the "Write-Foo" function is no longer available!
Get-Command -Module "childmod"

# Now go and manually modify source of ./childmod.psm1 to make it output "Foo2" instead of "Foo".

# This will *not* remove "Write-Bar", 
# but it also will *not* update "Write-Foo" if its source has since changed.
Import-Module "./childmod.psm1" -Function "Write-Foo"

# This confirms both "Write-Foo" and "Write-Bar" functions are available.
Get-Command -Module "childmod"

# This confirms that still the old source of Write-Foo is used, as "Foo" will be printed out instead of "Foo2".
Write-Foo

使用的 PowerShell 版本:

$PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.0.0
PSEdition                      Core
GitCommitId                    7.0.0
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

我考虑通过首先删除函数来模拟非破坏性强制导入,然后在没有 -Force 标志的情况下导入,但到目前为止我无法弄清楚如何删除单个导入的函数。

处理我的用例的正确方法可能是使用嵌套模块,如本技巧中所述:

Import-Module您应该避免从模块内调用。相反,将目标模块声明为父模块清单中的嵌套模块。声明嵌套模块可以提高依赖项的可发现性。

即使嵌套模块是正确的解决方案,它们也需要更多的努力。我想知道是否有更简单的解决方法。

4 年前相关未回答的问题:
带 -force 的 Import-Module 删除导入的模块功能?

我针对 PowerShell 打开的相关问题:“Import-Module -Force”删除了 $ErrorActionPreference 变量值。

标签: powershell

解决方案


推荐阅读