User Confirmation in Powershell

Built-in cmdlets usually offer the -Confirm parameter whenever you need user confirmation. When writing your own scripts, you might want to ask the eventual user of the script for confirmation yourself. This handy little function (store it in your profile!) allows you to ask for confirmation whenever, where-ever. (Try not to bug your users too much.)

# Description: Ask a user to answer a question with either yes or no.
 
# Example use: 
# If (Ask-YesOrNo)
# 	{ 
#	# User has confirmed
#	...
#	}
#	Else
#	{
#	# User did not confirm
#	...
#	}
 
Function Ask-YesOrNo
	{
	param([string]$title="Confirm",[string]$message="Are you sure?")
	$choiceYes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Answer Yes."
	$choiceNo = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Answer No."
	$options = [System.Management.Automation.Host.ChoiceDescription[]]($choiceYes, $choiceNo)
	$result = $host.ui.PromptForChoice($title, $message, $options, 1)
		switch ($result)
    	{
			0 
			{
			Return $true
			}
 
			1 
			{
			Return $false
			}
		}
	}

One thought on “User Confirmation in Powershell”

Leave a Reply