<#
Function : PauseForYesNo
Description: Prompt for
user input of "Y" or "N"
Note : Will not run from ISE, must run from
command prompt
Parameters :
-question : Question text to display to user
Returns :
Key pressed ("Y" or "N")
#>
function PauseForYesNo
{
param(
[Parameter(Mandatory=$true)][System.String]$question)
# Setup the question
write-host -f Yellow ("{0}?
" -f $question) -nonewline;
write-host -f Green "(Y or
N): " -nonewline;
# Read key input until "Y" or "N" pressed
do {
$key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
}
until (($key.Character -eq "Y") -or ($key.Character -eq "N"))
# Echo the key pressed
write-host -f White $key.Character;
# Return the key pressed
return $key.Character.ToString();
}
# Main
# Ask user if they are ready to do something
$Reply = PauseForYesNo -question "Are you
ready to do something";
# Based on user key pressed, do something or not
if ($Reply -eq "Y") {
write-host -f Green "
Do something!";
}
else {
write-host -f Red " Do nothing!";
}
|
These are random and hopefully useful tidbits from my daily SharePoint related development tasks. These will cover topics from the various languages and technologies I frequently use such as; SharePoint, C#, SQL, PowerShell, VBA, Javascript, and jQuery.
Wednesday, November 6, 2013
PowerShell Pause for Yes/No
Sometimes you need to ask a simple Yes or No question in a PowerShell script, I use the following function:
Labels:
PowerShell,
ReadKey,
Y or N
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment