A Better Confirmation Prompt for PowerShell Scripts

Many scripts require a simple confirmation before performing an action. Instead of using `Read-Host` and validating user input manually, PowerShell already provides a native solution through `PromptForChoice()`.

Share
A Better Confirmation Prompt for PowerShell Scripts

Many scripts require a simple confirmation before performing an action. Instead of using Read-Host and validating user input manually, PowerShell already provides a native solution through PromptForChoice().

The following helper function wraps it into a reusable Approve function that returns $true, $false, or aborts the script.

The Function

using namespace System.Management.Automation.Host

function Approve {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Title,

        [Parameter(Mandatory)]
        [string]$Question,

        [ValidateSet("Yes","No","Abort")]
        [string]$Default = "No"
    )

    $options = [ChoiceDescription[]](
        [ChoiceDescription]::new('&No','No'),
        [ChoiceDescription]::new('&Yes','Yes'),
        [ChoiceDescription]::new('&Abort','Abort the operation')
    )

    $defaultIndex = @{
        "No"    = 0
        "Yes"   = 1
        "Abort" = 2
    }[$Default]

    switch ($host.UI.PromptForChoice($Title, $Question, $options, $defaultIndex)) {
        0 { return $false }
        1 { return $true }
        2 { throw "Operation aborted by user." }
    }
}

Example

try {
    if (Approve `
        -Title "Restart Server" `
        -Question "Do you want to restart SRV01?" `
        -Default No)
    {
        Restart-Computer -ComputerName SRV01
    }
    else {
        Write-Host "Operation cancelled."
    }
}
catch {
    Write-Warning $_
}

Why use it?

  • Native PowerShell confirmation dialog
  • No manual input validation
  • Returns $true / $false
  • Supports a configurable default choice
  • Allows users to abort the operation cleanly

A small helper like this keeps interactive scripts cleaner and avoids repeating the same confirmation logic across your PowerShell projects.