powershell - 从 psm 函数的脚本 block 中定义的获取变量

标签 powershell module scope

我有以下代码:

$x = 'xyz'
& {
    $y = 'abc'
    foo
}

foo 函数定义在 foo.psm1 模块中,该模块在脚本 block 启动之前导入。

foo 函数中,我调用了 Get-Variable,它显示了 x 但没有显示 y。我尝试使用 -Scope 参数:LocalScriptGlobal0 - 这是我从文档中理解的本地范围,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/

相关文章:

c++ - 新变量的可访问性( "new"的范围)

Powershell 2.0 保存文件对话框样式

sql - Azure SQL Powershell,如何读取数据 View

linux - 短脚本、长模块还是长脚本、短模块?

module - 在项目的库根中声明的模块中使用 Rust 特性

javascript - JS 提升如何与 block 语句一起使用?

facebook - 为什么我请求 oauth 的电子邮件范围,Facebook 也显示我需要访问 friend 列表?

email - 在Powershell中使用电子邮件正文创建.bat文件

azure - 如何使用 PowerShell 获取 Azure 订阅的 TAG 值

python - 在 Python 2.7 中如何将文本 (.txt) 文件作为 .py 文件读取?