Variables imported from the module becomes $null, after the same module imported again

前端 未结 2 556
暖寄归人
暖寄归人 2021-01-17 18:41

I have a simple module: varExp.psm1

$var1 = 20

Export-ModuleMember -Variable var1

And I import this module into PS session:

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 19:02

    For me @manojlds gives the interesting part of the answer.

    Here are some more observations that can help @iank to sleep next night :

    when you first load the module you can use the following commande

    PS> $a = Import-Module .\varExp.psm1 -PassThru
    PS> $a.ExportedVariables.var1
    Name                           Value
    ----                           -----
    var1                           20
    

    Now you change the file .\varExp.psm1 to add a new var $var2=30 and also export it. If you stay in the same powershell you can test. $var2 does not appear.

    PS> $b = Import-Module .\varExp.psm1 -PassThru
    PS> $b.ExportedVariables
    Name                           Value
    ----                           -----
    var1                           
    

    For me as you do not remove the module (Remove-Module varexp) the module is reloaded from the memory information and vars are really replace but with nothing. If you remove the module or use -Force the module is reloaded from file. Try the following :

    PS> import-module .\varExp.psm1
    PS> Remove-Variable var1
    PS> import-module .\varExp.psm1
    PS> Get-ChildItem variable:
    ...
    var1
    ...
    

    $Var1 is recreated but not assign.

提交回复
热议问题