简体   繁体   English

在Powershell中评估变量中的变量

[英]Evaluate a variable within a variable in Powershell

I have the following variables: 我有以下变量:

[string]$eth_netmask = "ext_netmask"
[string]$ext_netmask = "255.255.252.0"

$($eth_netmask) is returning ext_netmask . $($eth_netmask)返回ext_netmask I was expecting 255.255.252.0 我期待255.255.252.0

What am I doing wrong? 我究竟做错了什么?
Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

The command $eth_netmask returns the value of the variable named eth_netmask. 命令$eth_netmask返回名为eth_netmask的变量的值。 The expression $(something) has nothing to do with variables, but instead evaluates the contents of the parentheses before evaluating the rest of the statement. 表达式$(something)与变量无关,而是在评估语句的其余部分之前先评估括号的内容。 That means that the statement $($eth_netmask) will evaluate in two steps: 1: $($eth_netmask) evaluates to the command "ext_netmask" 2: "ext_netmask" evaluates as a command which has the result of printing ext_netmask to the output. 这意味着该语句$($eth_netmask)将分两步求值:1: $($eth_netmask)求该命令"ext_netmask" 2: "ext_netmask"作为一条命令,其结果是将ext_netmask打印到输出。

This format is unnecessary since variables are normally resolved before the rest of the command anyway. 这种格式是不必要的,因为无论如何,变量通常在其余命令之前就已解析。 My recommendation would be to avoid needing to do this at all if there is any alternative. 我的建议是,如果有任何其他选择,则完全避免这样做。 Putting this kind of roundabout referencing into a piece of code can only cause problems. 将这种环形交叉引用放入一段代码中只会引起问题。 However, if you can't avoid it for some reason, it is possible to reference a variable the name of which is stored in another variable. 但是,如果由于某种原因无法避免使用该变量,则可以引用其名称存储在另一个变量中的变量。

[string]$eth_netmask = "ext_netmask"
[string]$ext_netmask = "255.255.252.0"

Get-Variable -Name $eth_netmask -ValueOnly

This is the point at which the $(something) syntax becomes useful. 这就是$(something)语法变得有用的地方。 If you need to use the value that you have just returned in another command, such as if the value was an ip that you were trying to ping, you might do something like this: 如果您需要使用刚在另一个命令中返回的值,例如,如果该值是您要ping的ip,则可以执行以下操作:

Test-Connection $(Get-Variable -Name $eth_netmask -ValueOnly)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM