我有以下代码:
$x = 'xyz'
& {
$y = 'abc'
foo
}
foo
函数定义在 foo.psm1
模块中,该模块在脚本 block 启动之前导入。
在 foo
函数中,我调用了 Get-Variable
,它显示了 x
但没有显示 y
。我尝试使用 -Scope
参数:Local
、Script
、Global
、0
- 这是我从文档中理解的本地范围,1
- 这是父范围。
如何在 foo
函数中获取 y
变量?
我不是在寻找解决方案,例如将其作为参数传递。我想要作为 Get-Variable
的东西,但遗憾的是由于某种原因它没有看到它。
UP
根据收到的评论,可能需要更多背景信息。
假设 foo 接收到一个使用 $using:
语法的 ScriptBlock
。
$x = 'xyz'
& {
$y = 'abc'
foo -ScriptBlock {
Write-Host $using:x
Write-Host $using:y
}
}
我正在“挖掘”这些变量,如下所示:
$usingAsts = $ScriptBlock.Ast.FindAll( { param($ast) $ast -is [System.Management.Automation.Language.UsingExpressionAst] }, $true) | ForEach-Object { $_ -as [System.Management.Automation.Language.UsingExpressionAst] }
foreach ($usingAst in $usingAsts) {
$varAst = $usingAst.SubExpression -as [System.Management.Automation.Language.VariableExpressionAst]
$var = Get-Variable -Name $varAst.VariablePath.UserPath -ErrorAction SilentlyContinue
}
这就是我使用 Get-Variable
的方式,在上述情况下,无法找到 y
。
最佳答案
模块在它们自己的范围域(又名 session 状态)中运行,这意味着它们通常不会看到调用者的变量——除非(模块外部)调用者直接在全局范围内运行。
- 有关 PowerShell 范围的概述,请参阅 this answer 的底部部分.
但是,假设您将模块中的函数定义为 advanced第一, 有一种方法可以访问调用者的状态,即通过 automatic $PSCmdlet
variable .
这是一个简化的示例,使用通过 New-Module
创建的动态 模块命令:
# Create a dynamic module that defines function 'foo'
$null = New-Module {
function foo {
# Make the function and advanced (cmdlet-like) one, via
# [CmdletBinding()].
[CmdletBinding()] param()
# Access the value of variable $bar in the
# (module-external) caller's scope.
# To get the variable *object*, use:
# $PSCmdlet.SessionState.PSVariable.Get('bar')
$PSCmdlet.GetVariableValue('bar')
}
}
& {
$bar = 'abc'
foo
}
上面的输出逐字 abc
,根据需要。
关于powershell - 从 psm 函数的脚本 block 中定义的获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68609996/