首页 > 解决方案 > 从实际变量中获取 powershell 变量名

问题描述

我试图弄清楚如何从对象本身获取 powershell 变量的名称。

我这样做是因为我正在对通过引用传递给函数的对象进行更改,所以我不知道该对象将是什么,并且我正在使用 Set-Variable cmdlet 将该变量更改为只读。

# .__NEEDTOGETVARNAMEASSTRING is a placeholder because I don't know how to do that.

function Set-ToReadOnly{
  param([ref]$inputVar)
  $varName = $inputVar.__NEEDTOGETVARNAMEASSTRING
  Set-Variable -Name $varName -Option ReadOnly
}
$testVar = 'foo'
Set-ToReadOnly $testVar

我已经浏览了很多类似的问题,但找不到任何具体回答这个问题的东西。我想完全在函数内部使用变量——我不想依赖传递额外的信息。

此外,虽然可能有更简单/更好的设置只读方式,但我一直想知道如何可靠地从变量中提取变量名,所以请专注于解决这个问题,而不是我在这个例子。

标签: powershellvariablespass-by-referencereadonlyvariable-names

解决方案


Mathias R. Jessen 的有用答案解释了为什么如果只传递它的就无法可靠地确定原始变量。

解决您的问题的唯一可靠解决方案是将变量对象而不是其值作为参数传递:

function Set-ToReadOnly {
  param([psvariable] $inputVar) # note the parameter type
  $inputVar.Options += 'ReadOnly'
}

$testVar = 'foo'
Set-ToReadOnly (Get-Variable testVar) # pass the variable *object*

如果您的函数与调用代码在同一范围内定义 -如果您在(不同的)模块中定义函数则不正确- 您可以更简单地仅传递变量名称并从父/祖先检索变量范围:

# Works ONLY when called from the SAME SCOPE / MODULE
function Set-ToReadOnly {
  param([string] $inputVarName)
  # Retrieve the variable object via Get-Variable.
  # This will implicitly look up the chain of ancestral scopes until
  # a variable by that name is found.
  $inputVar = Get-Variable $inputVarName
  $inputVar.Options += 'ReadOnly'
}

$testVar = 'foo'
Set-ToReadOnly testVar # pass the variable *name*

推荐阅读