PowerShell Prompts – Part 1

I always get nervous when I am writing scripts that could negatively impact users consuming a service, such as rebooting a server or restarting critical services.  I do my best to make sure the person running the script is aware of what is about to happen.  I feel the best when I can make sure the administrator has complete control and force them to confirm an action the script is about to execute.  In the past, I’ve implemented a very basic form of prompting for approval, here is an example from one of my older scripts:

$ConfirmPrompt = Read-Host "Are you sure you want to SHUT DOWN the above servers in the listed site(s)?  Type 'Yes' to continue"

if ($ConfirmPrompt -ne 'Yes') {
    Write-Warning "Confirm failed.  Script will quit."
    Exit
}

Obviously in this case the administrator has to explicitly type “Yes” in the prompt or the script will exit.  This is not very reliable.  What happens if the user wants to type in “Y” or does not spell the keyword properly?  The script would exit and the user would have to re-run the entire script because of a mistake.  In the first part of this two part post, I want to show a function I wrote to approve a yes/no command like this one.  To me, it feels a bit more ‘native PowerShell’, without having to build your own loop.

Function Approve-Action {
    param(
        $Message = "Are you sure you want to perform this action?"
    )
    [string[]]$Choices = @("&Yes","&No")
    $ListChoices = @()
    foreach ($Choice in $Choices) {
        $ListChoices += [System.Management.Automation.Host.ChoiceDescription]$Choice
    }
    $Results = $Host.ui.PromptForChoice("Confirm", $Message, $ListChoices, 0)
    return ($Choices[$Results] -match "Yes")
}

This function uses PowerShell’s built-in PromptForChoice method, which has it’s own input validation mechanism.  If the user types “Cancel” – the validation realizes this is not a valid option and will prompt the user again until a valid option is selected.  Worth mentioning is the “&” at the beginning of each choice input will allow the user to type the following letter to select that choice:

PowerShellConfirmPrompt1

The implementation is simple:

if (Approve-Action “OK to reboot this computer?”) {
    Restart-Computer
}

In part 2, I will cover a different implementation showing custom choices instead of a simple yes/no.