locked
Asking a Yes/No Question in CLI with a default answer RRS feed

  • Question

  • I'll start off by saying I feel like I missed a very obvious answer to this somewhere.

    I would like to ask a user if they would like to continue, with the default answer being yes.  For example:

         Do you want to continue? [Y/N] (Default is yes):


    I got close to what I wanted on this PowerShell Tip: https://technet.microsoft.com/en-us/library/ff730939.aspx (sorry I can't make that a link yet).  The only problem I have with this solution is that it is creating a GUI prompt for this, and I would rather stay in CLI where the rest of my script is working.  Any ideas?

    Monday, March 6, 2017 4:57 PM

Answers

  • Hi,

    there is indeed a simple way to do this:

    $caption = "Confirm"
    $message = "Are you sure?"
    $yes = new-Object System.Management.Automation.Host.ChoiceDescription "&Yes","help"
    $no = new-Object System.Management.Automation.Host.ChoiceDescription "&No","help"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)
    $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by UbuntuIrv Monday, March 6, 2017 5:44 PM
    Monday, March 6, 2017 5:07 PM

All replies

  • Hi,

    there is indeed a simple way to do this:

    $caption = "Confirm"
    $message = "Are you sure?"
    $yes = new-Object System.Management.Automation.Host.ChoiceDescription "&Yes","help"
    $no = new-Object System.Management.Automation.Host.ChoiceDescription "&No","help"
    $choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)
    $answer = $host.ui.PromptForChoice($caption,$message,$choices,0)

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by UbuntuIrv Monday, March 6, 2017 5:44 PM
    Monday, March 6, 2017 5:07 PM
  • Thanks for they reply Fred, but that is exactly what I found earlier on the linked post. I am looking for a solution that does not create a GUI prompt, but a prompt in CLI.
    Monday, March 6, 2017 5:10 PM
  • It doesn't if you're running the console version of PowerShell. Are you using the ISE?

    -- Bill Stewart [Bill_Stewart]


    Monday, March 6, 2017 5:29 PM
  • I was using the ISE, but looking at it in the console version, that's exactly what I wanted. Sorry about that confusion.
    Monday, March 6, 2017 5:45 PM