powershell - 如何在不删除以前从模块中导入的其他函数的情况下从模块中强制导入函数?
问题描述
在 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 变量值。
解决方案
推荐阅读
- python - Tensorflow 2:获取张量值
- swift - 如何将已知的位置和方向设置为 ARKit 的起点
- apache-kafka - 即使我在 porperties 文件中更改了端口,运行新的 kafka 服务器也会引发异常说端口 9092 alrady in use
- java - 如何检查spring boot应用程序在自动配置类中是否有某个注解
- php - 如果原始数据与其他人具有相同的名称字符串,如何回显原始数据
- java - 如何在 Java 中将 OpenSSH 私钥转换为 RSA 私钥?
- ruby - ArgumentError:通过 jenkins 执行 shell 运行 minitest 时的日期无效
- matlab - 找不到具有匹配签名的构造函数“Stateflow.State”。错误 Matlab
- twilio-programmable-chat - 未处理的承诺拒绝错误:“无法连接到 twilsock”
- r - Leaflet r地图保存问题