Evaluate a variable within a variable in Powershell

早过忘川 提交于 2021-01-28 07:15:16

问题


I have the following variables:

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

$($eth_netmask) is returning ext_netmask. I was expecting 255.255.252.0

What am I doing wrong?
Thanks for the help in advance!


回答1:


The command $eth_netmask returns the value of the variable named 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. 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.

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. 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:

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


来源:https://stackoverflow.com/questions/20340525/evaluate-a-variable-within-a-variable-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!