5

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
  • What are you trying to accomplish? Commented Dec 3, 2013 at 0:24

1 Answer 1

10

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)
Sign up to request clarification or add additional context in comments.

3 Comments

That's awesome. You fixed my issue. I understand that what I am doing is non-standard but its the only way I knew how to make the function work. In case you are wondering. Here is the real code. I was just trying to hone in on my real problem!
for ($index = 0; $index -lt $numInterfaces; $index++) { $y = $index + 1 $destconffile="$destdir\ifcfg-eth$index" $eth_vlanname=$headernames[$y] $eth_vlanid="$($eth_vlanname)_vlanid" $eth_netmask="$($eth_vlanname)_netmask" Copy-Item ifcfg-ethx $destconffile (get-content $destconffile ) | foreach-object {$_ -replace "ethx" , "eth$index"} | set-content $destconffile
[string]$ipaddr=$valuesnames[$y] add-content $destconffile "nIPADDR=$ipaddr" [string]$realnetmask=get-variable -Name $eth_netmask -ValueOnly add-content $destconffile "nNETMASK=$realnetmask" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.