再次导入同一个模块后,从模块导入的变量变为 $null [英] Variables imported from the module becomes $null, after the same module imported again
问题描述
我有一个简单的模块:varExp.psm1
I have a simple module: varExp.psm1
$var1 = 20
Export-ModuleMember -Variable var1
Export-ModuleMember -Variable var1
然后我将这个模块导入到 PS 会话中:
And I import this module into PS session:
PS>导入模块 .\varExp.psm1
PS> Import-Module .\varExp.psm1
然后
PS>$var1
20
但是在我第二次导入之后
But after I import it second time
PS>导入模块 .\varExp.psm1
PS> Import-Module .\varExp.psm1
PS>$var1
PS>
$var1 变为空...
$var1 becomes null...
有人知道这是怎么回事吗?(PS2.0)
Anybody knows what is going on here? (PS2.0)
有解决方法:使用 Import-Module .\varExp.psm1 -Force
强制重新加载,并测试之前是否加载了模块:if(-not (Get-Module varExp)) { 导入模块 .\varExp.psm1 }
.但我希望在简单的情况下得到 $null 值背后的一些原因.
There are workarounds: Forcing reloading with Import-Module .\varExp.psm1 -Force
, and testing if module was loaded before: if(-not (Get-Module varExp)) { Import-Module .\varExp.psm1 }
. But I was hoping to get some reason behind $null value in simple case.
推荐答案
我不知道到底发生了什么,但是当你重新导入一个模块时,你必须使用 -Force
.
I don't know exactly what happens, but when you are re-importing a module , you have to use -Force
.
当您包含 -verbose
时,您可以看到两者之间的区别:
When you include -verbose
you can see the difference between the two:
PS> import-module .\test -Verbose
VERBOSE: Importing variable 'var1'.
用力:
PS> import-module .\test -Verbose -Force
VERBOSE: Removing the imported "var1" variable.
VERBOSE: Loading module from path 'C:\test\test.psm1'.
VERBOSE: Importing variable 'var1'.
文档确实说明了以下内容:
The documentation does say the following:
如果您将具有相同名称和相同类型的成员导入到您的会话,Windows PowerShell 默认使用最后导入的成员.变量和别名被替换了,原来没有可访问.
If you import members with the same name and the same type into your session, Windows PowerShell uses the member imported last by default. Variables and aliases are replaced, and the originals are not accessible.
我认为原件不可访问
意味着当你重新导入模块时,这个$var1
是不可访问的.
I think the originals are not accessible
means in this $var1
is not accessible when you re-import the module.
这篇关于再次导入同一个模块后,从模块导入的变量变为 $null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!