powershell - 从实际变量中获取 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
我已经浏览了很多类似的问题,但找不到任何具体回答这个问题的东西。我想完全在函数内部使用变量——我不想依赖传递额外的信息。
此外,虽然可能有更简单/更好的设置只读方式,但我一直想知道如何可靠地从变量中提取变量名,所以请专注于解决这个问题,而不是我在这个例子。
解决方案
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*
推荐阅读
- java - 我如何知道 Java 类的注释?
- laravel - 只有两种方法但使用 Route::apiResource 是不好的做法吗?
- php - 如何将一个选择元素与另一个选择语句相关联
- laravel - 从私有存储问题 Laravel 5.7 获取文件
- java - 如何在 android 中创建/写入和读取 word(具有 .doc 和 .docx 扩展名)文件?
- reactjs - 使用 React Typescript 的扩展运算符
- angular - 使用 agm-core (Angular Google Maps) 我如何在 agm-polyline 上使用箭头
- python - Python - 复制元素的属性并粘贴到另一个文本文件
- angular - ionic cordova angular html2canvas 和 pdfMake 在手机上的 pdf 文件中下载屏幕截图
- html - CSS 覆盖命令