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

Welcome Forums General PowerShell Q&A 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

4 years, 2 months ago.

  • Author
  • #21816

    Points: 0
    Rank: Member

    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 "Clusters on {$VIServer}:"
    Get-Cluster | Sort-Object Name | Write-Host
    Write-Host "Type Cluster for the VM from those listed above:"
    $Cluster = Read-Host

    This gives a list of existing clusters like:

    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.


  • #21818

    Points: 0
    Rank: Member

    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:

  • #21820

    Points: 0
    Rank: Member

    GUI interface is definitely better. Thanks Dave

The topic ‘Comparing user input with a list of strings, looking for a match’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort