2

There is a hashtable:

$Main = @{
    One = 'One Value'
    Two = @{    
        Two = 'Two Value'
        Tree = @{        
            Tree = 'Tree Value'
        }    
    }
}

Why can't I get the values this way?

# It works
$Want = 'One'
$Main.$Want

# This does not work. I get a void
$Want = 'Two.Two'
$Main.$Want

# And that of course doesn't work either
$Want = 'Two.Tree.Tree'
$Main.$Want

How to modify $Want string so that it turns out to be possible (for example, [Something]$Want = 'Two.Tree.Tree' and I get the value $Main.$Want of Tree Value).

At the moment, I have made such a decision. But for sure there are shorter and faster solutions provided.

$Main = @{
    One = 'One Value'
    Two = @{    
        Two = 'Two Value'
        Tree = @{        
            Tree = 'Tree Value'
        }    
    }
}

# $Want = 'One'
# $Want = 'Two.Two'
$Want = 'Two.Tree.Tree'

$Want = $Want -Split '\.'
$Want = Switch ( $Want.Length ) {

    1 { $Main.($Want[0]) }
    2 { $Main.($Want[0]).($Want[1]) }
    3 { $Main.($Want[0]).($Want[1]).($Want[2]) }
}

$Want

# Result 'Tree Value'

1 Answers1

1

Use Invoke-Expression:

$Want = 'Two.Two'

Invoke-Expression ('$Main.' + $Want)
f6a4
  • 1,684
  • 1
  • 10
  • 13
  • 2
    That's certainly the easiest way, but it should come with a warning, borrowed from the linked post: While the simplest solution is to use `Invoke-Expression`, [`Invoke-Expression` should generally be avoided](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/); it is safe *in this particular scenario*, because you fully control the input string, but it is better to form a habit of _not_ using `Invoke-Expression`, especially given that in most situations there are alternatives that are both more robust and more secure. – mklement0 Jan 20 '20 at 13:38
  • mklement is right, do not use Invoke-Expression for user Input etc., only for expressions controlled by the programmer. – f6a4 Jan 20 '20 at 14:02
  • Thank. I read now about the features of using the ```Invoke-expression``` here: https://adamtheautomator.com/invoke-expression/amp/ – Кирилл Зацепин Jan 20 '20 at 14:27