1

Is there a choice equivalent? I do not want to create a batch file but a script for PowerShell ISE. What can I do?

aynber
  • 22,380
  • 8
  • 50
  • 63
Michael S.
  • 589
  • 8
  • 25

2 Answers2

0

Choice.exe is not a native PowerShell command but an interactive console application.

Try e.g.:

Start-Process -Wait "choice.exe"

Or use something like Read-Host instead:

$Choice = Read-Host -Prompt 'Input your choice'

Also see: http://powershell.com/cs/blogs/tips/archive/2012/08/17/disabling-console-apps-in-powershell-ise.aspx

iRon
  • 20,463
  • 10
  • 53
  • 79
0

Generally, you don't strictly need a choice.exe equivalent in PowerShell, given that it is a standard executable that ships with Windows (C:\WINDOWS\system32\choice.exe): you can simply call it from PowerShell - except from the ISE, where interactive console applications are fundamentally unsupported.

For example (in a regular console window or Windows Terminal):

# Prompt the user:
choice /c IRC  /m 'An error occurred: [I]gnore, [R]etry, or [C]ancel'

# Handle the response, which is implied by choice.exe's exit code.
# Note:
#  * An external program's exit code is reflected in the 
#    automatic $LASTEXITCODE variable in PowerShell.
#  * choice.exe sets its exit code to 1 if the first choice was selected,
#    2 for the second, ...
switch ($LASTEXITCODE) {
  1 { 'Ignoring...'; <# ... #>; break }
  2 { 'Retrying...'; <# ... #>; break }
  default { Write-Warning 'Canceling...'; exit 2 }
}

PowerShell does have a similar feature, $host.ui.PromptForChoice(), but:

  • its syntax is a bit awkward
  • typing a selection letter must be submitted with Enter, whereas with choice.exe typing just typing the letter is enough.
  • while it works in the ISE too, the prompt is presented as a modal GUI dialog.

For example (the analog of the above):

# Prompt the user.
# Note: 
#  * The "&" in each choice string designates the selection letter.
#  * The 2 argument is the 0-based index of the *default* choice, 
#    which applies if you just press ENTER.
#  * Similarly, the return value is the *0*-based index of the selected choice
#   (0 for the first, 1 for the second, ...)
$response =
  $host.ui.PromptForChoice(
    "Error",  # title
    "An error occurred:", # prompt text
    ('&Ignore', '&Retry', '&Cancel'), # choice strings,
    2  # default choice
  )

# Handle the response.
switch ($response) {
  0 { 'Ignoring...'; <# ... #>; break }
  1 { 'Retrying...'; <# ... #>; break }
  default { Write-Warning 'Canceling...'; exit 2 }
 }

To make the above easier in the future, GitHub issue #6571 discusses providing a dedicated Read-Choice cmdlet or enhancing Read-Host (which currently only supports free-form input).

However, note that only a future PowerShell (Core) version would receive such an enhancement, which means that you won't be able to use it in the ISE.

mklement0
  • 382,024
  • 64
  • 607
  • 775