PowerShell:无法使用变量 $Using:(Get-Variable -Name $Name)

问题描述 投票:0回答:1

在 ForEach-Object -Parallel{} 中,我尝试调用在函数之前定义的不同名称的变量。这需要

$Using:Name
从函数外部引入变量。

但是,当尝试使用

$Using:$Name
$Using:(Get-Variable -Name $Name)
时,它会提供错误:“变量引用无效。':' 后面没有跟有效的变量名称字符。请考虑使用 ${} 来分隔名称。”

当尝试使用

${Using:$Name}
时,
{}
给出文字字符串并且不起作用。 试图使其工作的其他变体要么提供无效的相同变量引用,要么该变量为空。

尝试过的变体:

$Using:{(Get-Variable -Name $Name)}
$Using:(Get-Variable -Name $Name)
Get-Variable -Name "Using:$Name"
Get-Variable -Name Using:$Name

代码示例:

$0IndexA = @(45,51,57)
$1IndexA = @(1490,1901,1903)

0..1 | Foreach-Object -Parallel {
    $ParallelNumber = $_ # Used for readability

    For ($c = 0; $c -le (Get-Variable $ParallelNumber"IndexA").value.count; $c++){
        Get-Variable -Name $ParallelNumber"IndexA"[$c]
    }
}

错误:找不到名为“0IndexA”的变量。

尝试使用-scope 1 错误:“范围编号‘1’超出了活动范围的数量。(参数‘范围’)实际值为 1。”

powershell parallel-processing using foreach-object
1个回答
0
投票

您正在寻找变量间接,即通过存储在另一个变量中的名称间接引用变量的能力。

但是,在

$using:
范围的上下文中,这是 支持的:
:
必须 是一个 literal 变量名称。

正如 Darin 所建议的,一种解决方法是在调用者的作用域中使用哈希表,将输入对象映射到要用于它们的值。:

# Helper hashtable that maps the inputs to ForEach-Object -Parallel
# to values.
$valuesHash = @{
  0 = @(45,51,57)
  1 = @(1490,1901,1903)
}

0..1 | Foreach-Object -Parallel {
  $values = ($using:valuesHash)[$_]
  "$values" # sample output; -> '45 51 57', '1490 1901 1903'
}
© www.soinside.com 2019 - 2024. All rights reserved.