0

I'm currently learning PowerShell and I can't work out how to combine a string and a variable to pull information from an existing variable.

The user input will just be a number, so 1,2,3 etc. which I need to append to the end of $option which will pull the title information from the variable $optionX.

So far everything I've tried just interprets it as a string and print $OptionX into the console, as opposed to the value held by $OptionX.

So for example:

    function Title{
    Write-host "$OptionName for:"$computerSystem.Name -BackgroundColor DarkCyan 
}


function GetMenu { 

    # Set the menu options
    $Option1 = "1) System Information"

    # Get menu selection
    $Navigation = Read-Host "Enter Selection" 

    ToolBox 

}

function ToolBox{ 
    Clear-Host 
    switch ($Navigation){ 
        1 { #Script 1
            Title

          } 
Jacob
  • 1,182
  • 12
  • 18
  • Stop stop, you're trying to make "variable variables" because you don't understand hashtables. Go read https://stackoverflow.com/questions/40794859/how-to-use-a-for-loop-variable-to-help-define-another-variable#comment68819688_40794859 and my linked answer, it applies here too, and your life and code will be enormously easier, clearer (and faster) for it. – TessellatingHeckler Jun 21 '17 at 18:54

2 Answers2

0

I figured out how to do it, I'm not sure if it's the best method but it does what I need it to do.

function Title{
    $OptionCombine = "Option"+$Navigation
    $OptionName = Get-variable $OptionCombine -ValueOnly
    Write-host "$OptionName for:"$computerSystem.Name -BackgroundColor DarkCyan 
}
Jacob
  • 1,182
  • 12
  • 18
0

You can do what you do in the self-answer. I would suggest using a hash-map for it though - seems cleaner to me. (I have no idea what the $computersystem.Name-part is, so I just left it in):

function Title{
    Write-host "$($Options[$Navigation]) for:"$computerSystem.Name -BackgroundColor DarkCyan 
}

function GetMenu { 
    # Set the menu options
    $Options = @{
        "1" = "1) System Information"
        "2" = "2) Something else"
    }

    # Get menu selection
    $Navigation = Read-Host "Enter Selection" 

    ToolBox 

}

function ToolBox{ 
    Clear-Host 
    switch ($Navigation){ 
        1 { #Script 1
            Title
          }
    }
}

For the rest of your script I can see that you are using Global Variables extensively, which I would avoid (it will confuse you, makes it harder to understand what is going on, and many other reasons not to use them). Look into using parameters for your functions, using the snippet menu (CTRL+J) in Powershell ISE will make a quick function skeleton for you. When you want to develop further in Powershell functions look into the Cmdlet (advanced function) template in the same menu.

Zerqent
  • 483
  • 3
  • 9
  • That looks a lot more manageable, I'll have a play around with it, and do some reading into hash tables/maps but thank you so much! – Jacob Jun 21 '17 at 21:29