Skip to content

Instantly share code, notes, and snippets.

@jcefoli
Created August 15, 2014 22:33
Show Gist options
  • Save jcefoli/fb9400aafee2ac585db3 to your computer and use it in GitHub Desktop.
Save jcefoli/fb9400aafee2ac585db3 to your computer and use it in GitHub Desktop.
Template for Yes/No Choice input in batch files
@ECHO OFF
:start
SET choice=
SET /p choice=Do something? [N]:
IF NOT '%choice%'=='' SET choice=%choice:~0,1%
IF '%choice%'=='Y' GOTO yes
IF '%choice%'=='y' GOTO yes
IF '%choice%'=='N' GOTO no
IF '%choice%'=='n' GOTO no
IF '%choice%'=='' GOTO no
ECHO "%choice%" is not valid
ECHO.
GOTO start
:no
ECHO Do all of the no things here!
PAUSE
EXIT
:yes
ECHO Do all of the yes things here!
PAUSE
EXIT
@Pilkja
Copy link

Pilkja commented Jun 10, 2024

@jcefoli

I would recommend using PowerShell as a much more modern and capable way of scripting

Could you give a hint, how one would write an equal batch file for PowerShell? Would that file use the same extension *.bat?
Thanks!

@jcefoli
Copy link
Author

jcefoli commented Jun 11, 2024

I would recommend using PowerShell as a much more modern and capable way of scripting

Could you give a hint, how one would write an equal batch file for PowerShell? Would that file use the same extension *.bat? Thanks!

PowerShell and Batch are two different things. Batch files are handled by cmd.exe and you can double click them to run a string of commands. They are very old and it's not as good as linux bash or PowerShell

PowerShell scripts have the .ps1 extension. You cannot just click them like a batch file, and you must call them from the powershell console.

There are much more elegant ways to create a menu in Powershell, but porting the code above over to parity looks like so:

$choice = ""
while ($choice.ToUpper() -ne "Y" -and $choice.ToUpper() -ne "N") {
    $choice = Read-Host "Do Something (Y/N)"

    if ($choice.ToUpper() -eq "Y") {
        Write-Host "You chose yes"
    } elseif ($choice.ToUpper() -eq "N") {
        Write-Host "You chose no"
    } else {
        Write-Host "$choice is not valid"
    }
}

@ChristineRos
Copy link

Thank you so much for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment