Wednesday, January 16, 2019

Simple Choice in Powershell

This demonstrates how to prompt for a choice in a loop.

$the_data = @("a1", "b2", "c3", "d4")


## The following four lines only need to be declared once in your script.
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Description."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No","Description."
$cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel","Description."
$all = New-Object System.Management.Automation.Host.ChoiceDescription "&All", "Description."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no, $all, $cancel)


$last_choice = -1
foreach ($d in $the_data)
{
    if ($last_choice -ne 2)
    {
        $title = "Processing Registy"
        $message = ("Do you want to delete: $d")
        $last_choice = $host.ui.PromptForChoice($title, $message, $options, 0)
    }

    if ($last_choice -eq 1)
    {
        continue
    }
    elseif ($last_choice -eq 3)
    {
        break
    }

    "Deleting: $d"
}

## Use the following each time your want to prompt the use
# $title = "Title"; $message = "Question?"
# $result = $host.ui.PromptForChoice($title, $message, $options, 0)
# switch ($result) {
# 0{
# Write-Host "Yes"
# }1{
# Write-Host "No"
# }2{
# Write-Host "Cancel"
# }
# }