Powershell 每个脚本的模块作用域都会重复
我有一个模块和运行简单用户脚本的脚本。我想让用户脚本尽可能简单,这就是为什么我使用带有-Global标志的导入模块。我对模块私有变量有问题。在我的例子中,这个变量有两个副本。我只能得到一份吗 下面是一个简单的例子。您可以通过将3个文件放在同一文件夹中并执行ScriptRunner.ps1来运行 模块.psm1 ScriptRunner.ps1 UserScript.ps1 在我的示例函数New Something sets UserScriptFailed to$true中。但一旦UserScript.ps1完成,ScriptRunner.ps1就会看到$false值 输出:Powershell 每个脚本的模块作用域都会重复,powershell,powershell-module,Powershell,Powershell Module,我有一个模块和运行简单用户脚本的脚本。我想让用户脚本尽可能简单,这就是为什么我使用带有-Global标志的导入模块。我对模块私有变量有问题。在我的例子中,这个变量有两个副本。我只能得到一份吗 下面是一个简单的例子。您可以通过将3个文件放在同一文件夹中并执行ScriptRunner.ps1来运行 模块.psm1 ScriptRunner.ps1 UserScript.ps1 在我的示例函数New Something sets UserScriptFailed to$true中。但一旦UserScr
Write-Var output: True
ScriptRunner output: False
您可以尝试点源要检查的脚本:
function Invoke-UserScript
{
param($Path)
$Script:UserScriptFailed = $false
# Sourcing may add the functions to the current scope
. $Path
& $Path
return $Script:UserScriptFailed
}
这是预期的-$script:从模块的导出函数中调用时引用模块作用域,并且ScriptRunner.ps1不是module@MathiasR.JessenScriptRunner.ps1不是模块的一部分,也不是指UserScriptFailed变量,我们在这里没有问题。问题是&$Path会创建此变量的新副本。这一行在一个模块中。您可以使用Export ModuleMember-Variable…,但我不确定脚本:scope如何工作。另一种方法是将UserScriptFailed移动到全局范围,但这不是最好的方法…您想实现什么?如果您想在多个ps1文件之间共享一个变量,可以尝试将该变量作为-参数注入
New-Something
Write-Var
Write-Var output: True
ScriptRunner output: False
function Invoke-UserScript
{
param($Path)
$Script:UserScriptFailed = $false
# Sourcing may add the functions to the current scope
. $Path
& $Path
return $Script:UserScriptFailed
}