If 声明反对动态变量

编程入门 行业动态 更新时间:2024-10-23 11:24:28
本文介绍了If 声明反对动态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试做类似于以下的事情......

I am attempting to do something similar to the following ...

New-Variable -Name "state_$name" -Value "True" if ("state_$name" -eq "True") { Write-Host "Pass" } else { Write-Host "Fail" }

我已经尝试了多种不同的方法,但它并没有完全按照我希望的方式工作.我需要编写 if 语句来说明动态变量,因为这些值将在 foreach 循环内更改.

I have attempted this a number of different ways but it is not working exactly how I would like it to work. I need to write the if statement to account for a dynamic variable as these values will change inside of a foreach loop.

我在上面提供了一个简单的例子来证明概念.

I have provided a simple example above for proof of concept.

推荐答案

替换

if ("state_$name" -eq "True") {

与:

if ((Get-Variable -ValueOnly "state_$name") -eq "True") {

也就是说,如果你的变量名只是间接,通过一个可扩展的字符串,你不能直接引用它(就像你通常使用 $ 符号一样) -您需要通过Get-Variable获取其值,如上所示.

That is, if your variable name is only known indirectly, via an expandable string, you cannot reference it directly (as you normally would with the $ sigil) - you need to obtain its value via Get-Variable, as shown above.

但是,正如 JohnLBevan 指出的那样,您可以存储变量 object在另一个(非动态)变量中,以便您可以通过 .Value 属性获取和设置动态变量的值.在New-Variable调用中添加-PassThru直接返回变量对象,不需要后续的Get-Variable调用:

However, as JohnLBevan points out, you can store the variable object in another (non-dynamic) variable, so that you can then get and set the dynamic variable's value via the .Value property. Adding -PassThru to the New-Variable call directly returns the variable object, without the need for a subsequent Get-Variable call:

$dynamicVarObject = New-Variable -Name "state_$name" -Value "True" -PassThru if ($dynamicVarObject.Value -eq "True") { "Pass" } else { "Fail" }

也就是说,以这种方式创建变量通常有更好的替代方法,例如使用哈希表:

$hash = @{} $hash.$name = 'True' if ($hash.$name -eq 'True') { 'Pass' } else { 'Fail' }

更多推荐

If 声明反对动态变量

本文发布于:2023-11-28 07:27:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   声明   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!