powershell - 同一个模块再次导入后,从模块导入的变量变为$null

标签 powershell powershell-2.0

我有一个简单的模块:varExp.psm1

$var1 = 20

Export-ModuleMember -Variable var1


我将此模块导入 PS session :

PS> Import-Module .\varExp.psm1


然后

PS> $var1

20


但是在我第二次导入它之后

PS> Import-Module .\varExp.psm1

PS> $var1

PS>


$var1 变为空...
有人知道这里发生了什么吗? (PS2.0)
编辑:有解决方法:使用 Import-Module .\varExp.psm1 -Force 强制重新加载,并测试之前是否加载了模块:if(-not (Get-Module varExp)) { Import-Module .\varExp.psm1 } .但我希望在简单的情况下得到 $null 值背后的一些原因。

最佳答案

我不知道究竟会发生什么,但是当您重新导入模块时,您必须使用 -Force .

当您包括 -verbose您可以看到两者之间的区别:

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'.

该文档确实说明了以下内容:

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.



我认为 originals are not accessible表示在此 $var1重新导入模块时无法访问。

关于powershell - 同一个模块再次导入后,从模块导入的变量变为$null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8001496/

相关文章:

Powershell "join"

powershell - 限制在 powershell 中运行的 Start-Process 数量

mysql - 在 powershell 脚本中运行 mysqldbcompare

powershell - PowerShell 中的复杂变量字符串

powershell - PowerShell:为每个计数器计算rawvalue属性的连续值之间的增量

PowerShell:如何获得 if else 构造正确?

powershell - PowerShell 2.0 中的位移位

Powershell:检查计算机是否已注销

powershell - 在 Powershell 中获取两个日期之间的天数差异

powershell - 使用Register-WmiEvent通知脚本何时开始执行