Skip to content

Instantly share code, notes, and snippets.

@ijprest
Created April 13, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijprest/5882a06496b468415021 to your computer and use it in GitHub Desktop.
Save ijprest/5882a06496b468415021 to your computer and use it in GitHub Desktop.
function Confirm-Host {
<#
.SYNOPSIS
Prompts the user to OK or Cancel an operation via the host.
.DESCRIPTION
Prompts the user to OK an operation by hitting ENTER or cancel
it by hitting ESC.
.EXAMPLE
if(Confirm-Host) { ... }
.OUTPUTS
[bool]
#>
[CmdletBinding()]
param(
# Prompt string to display to the user
[string]$Prompt = "Press ENTER to continue, or ESC to cancel",
# Timeout value, in seconds
[int]$Timeout = 0,
# Default value to use if the operation times-out
[bool]$TimeoutDefault = $true,
# The color to use for the prompt
[ConsoleColor]$PromptColor = 'DarkGray'
)
$oldcolor = $host.UI.RawUI.ForegroundColor
$oldctrlc = [console]::TreatControlCAsInput
$enterdown = $false
$escdown = $false
$timeoutCount = $timeout * 20
$result = $TimeoutDefault
[console]::TreatControlCAsInput = $true
Invoke-Command { $host.UI.RawUI.FlushInputBuffer() } -ErrorAction SilentlyContinue
try {
$host.UI.RawUI.ForegroundColor = $PromptColor
Write-Host -NoNewline "$prompt"
:outerloop while((-not $timeout) -or ($timeoutCount -gt 0)) {
if($timeout -and (($timeoutCount % 20) -eq 0)) {
Write-Host -NoNewline "`r$prompt ($([int]($timeoutCount/20))) `r"
}
Start-Sleep -Milliseconds 50
$timeoutCount = $timeoutCount - 1
while($host.ui.RawUI.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,IncludeKeyDown,NoEcho")
if($key.KeyDown) {
if($key.VirtualKeyCode -eq 27) { $escdown = $true }
if($key.VirtualKeyCode -eq 13) { $enterdown = $true }
} else {
if(($key.VirtualKeyCode -eq 27) -and $escdown) { $result = $false; break outerloop }
if(($key.VirtualKeyCode -eq 13) -and $enterdown) { $result = $true; break outerloop }
}
}
}
} finally {
Write-Host "`r$prompt "
$host.UI.RawUI.ForegroundColor = $oldcolor
[console]::TreatControlCAsInput = $oldctrlc
}
return $result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment