Comparing user input with a list of strings, looking for a match

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Ross Murray Ross Murray 1 year, 11 months ago.

  • Author
    Posts
  • #21816
    Profile photo of Ross Murray
    Ross Murray
    Participant

    Hi folks. I am trying to write a script which can deploy VM's from templates in VMware. I'm new to this, so trying to keep it as simple as possible. I'm using VMware PowerCLI for this, and am stuck with how to compare input from a user with the result of a Get-Cluster cmdlet.

    So I have:

    # List and prompt for Cluster
    Write-Host
    Write-Host "Clusters on {$VIServer}:"
    Write-Host
    Get-Cluster | Sort-Object Name | Write-Host
    Write-Host
    Write-Host "Type Cluster for the VM from those listed above:"
    $Cluster = Read-Host

    This gives a list of existing clusters like:
    Cluster1
    Cluster2
    Cluster3

    If the user types Cluster2, how can I compare that typed input with this list of Clusters? I want it to continue with the rest of the script if there is a match, or prompt again for the Cluster if there is no match (also providing the user with an explanation for why they need to enter it again.

    Any help would be greatly appreciated.

    Ross

  • #21818
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    If you want to implement that yourself, you can store a list of valid values in a variable and use either the -contains or -in operators to detect whether the user typed a valid option. That's not a particularly great user experience, though (having to type out a whole name instead of just entering a number or clicking a button.) If you don't mind a tiny bit of GUI interaction, here's an easy way to give people a list to select from in PowerShell 3.0 and onward:

    $selection = Get-Cluster | Sort-Object Name | Select-Object Name | Out-GridView -PassThru -Title 'Select a cluster'
    

    If the user presses the Cancel button on that dialog, $selection will be $null; you'll probably want some code to detect and handle that case.

    If you want to have a text menu rather than GUI in powershell.exe, you can use the $host.UI.PromptForChoice() method, but it's a little bit more involved to set up your selections. There's an example of this over on TechNet: http://technet.microsoft.com/en-us/library/ff730939.aspx

  • #21820
    Profile photo of Ross Murray
    Ross Murray
    Participant

    GUI interface is definitely better. Thanks Dave

You must be logged in to reply to this topic.