初始化将要导出的Powershell模块变量

Pau*_*Duc 4 powershell

我无法理解为什么我无法实现以下目标:

在模块中创建一组变量。让模块中的函数执行某项操作,并使用更改后的值更新父范围变量。将模块导入到调用相同功能的脚本中,并使更新后的值可用于导入模块的脚本。

例如,模块库具有以下内容:

$psVarx = -1

function Init {

   $psVarx = 2
   $script:psVarx = $psVarx
}
Run Code Online (Sandbox Code Playgroud)

Export-Member -variable $psVarx

使用该模块的脚本具有以下内容:

Import-Module Lib -Force

Init

"psVarx is {0}" -f $psVarx
Run Code Online (Sandbox Code Playgroud)

收到的输出是

psVarx is -1

问题是,如果我在模块中更新了变量的脚本作用域副本,为什么使用模块的脚本看不到变量的更新值?我很确定问题与范围界定有关。我在这里想念什么?

在模块需要工作以初始化自身并设置变量的情况下,建议使用什么方法初始化模块变量,然后将这些变量提供给导入模块的代码?

在这种特殊情况下,我想在模块中初始化许多变量,然后导出新初始化的值。

Χpẘ*_*Χpẘ 5

在PowerShell V3中,以下工作:

$psVarx = -1

function Init {

   $psVarx = 2
   $script:psVarx = $psVarx
}
Export-ModuleMember -variable psVarx -Function init
Run Code Online (Sandbox Code Playgroud)

请注意,psVarx(not $psVarx)传递给了Export-modulemember(not Export-Member)。也Init被指定。