脚本(.ps1)导入ModuleA,它导入ModuleB。 从脚本我可以看到ModuleB中的一个函数(带有Get-Command),但它被列为属于ModuleA。我也可以修改/删除该功能。 当执行进入ModuleA时,ModuleB中的函数被列为属于ModuleB(通过Get-Command)并恢复到原始状态。
这是设计吗?
Import-Module .\Import-First.psm1
Get-Command -Module "Import-First" # Write-Greetings and Write-Goodbye
Get-Command -Module "Import-Second" # no functions found
Get-Command -Name "Write-Goodbye" # Write-Goodbye (module = Import-First) ***is this by design?***
Remove-Item "function:\Write-Goodbye"
Get-Command -Module "Import-First" # Write-Greetings
Get-Command -Module "Import-Second" # no functions found
Get-Command -Name "Write-Goodbye" # error: function doesn't exist (expected)
Write-Greetings
Import-Module .\Import-Second.psm1
function Write-Greetings
{
Write-Host "hello world!" # hello world!
Get-Command -Module "Import-First" # Write-Greetings
Get-Command -Module "Import-Second" # Write-GoodBye
Get-Command -Name "Write-GoodBye" # Write-GoodBye (module = Import-Second) ***module changed since execution scope changed***
Write-GoodBye
}
function Write-Goodbye
{
Write-Host "bye bye!"
}
答案 0 :(得分:0)
是。在模块中导入模块时,嵌套模块的功能就像它们是父模块的一部分一样。导入模块时,可以将该模块的特定成员导出到全局范围。删除这些全局范围的对象不会影响内部模块。
我建议不要嵌套模块。分别导入每个模块。最好为每个模块创建一个自定义Import-Module.ps1
脚本,该脚本首先导入该模块的依赖项,然后导入模块本身。所以,在你的情况下,
& Import-Second.ps1
Import-Module First.psm1
Import-Module Second.psm1
& .\Import-First.ps1
Get-Command -Module "First" # Write-Greetings and Write-Goodbye
Get-Command -Module "Second" # no functions found
Get-Command -Name "Write-Goodbye" # Write-Goodbye (module = Import-First) ***is this by design?***
& .\Import-Second.ps1
Get-Command -Module "First" # Write-Greetings
Get-Command -Module "Second" # Write-Goodbye found
Get-Command -Name "Write-Goodbye" # function exists because it is in Second module.
Write-Greetings
您不应该创作具有冲突名称的模块。第二个模块将始终覆盖第一个模块函数/ cmdlet /变量,如果它们之间的命名相似。您可以使用Import-Module
的{{1}}参数来防止代码被覆盖。