Skip to content

Powershell script to ask yes or no and execute code based on the answer

Here’s an example of a PowerShell script that prompts the user with a yes/no question and executes different code based on the answer

$choice = Read-Host "Do you want to proceed? (Y/N)"

if ($choice -eq "Y" -or $choice -eq "y") {
    # Code to execute if the answer is yes
    Write-Host "Proceeding with the operation..."
    # Add your code here
elseif ($choice -eq "N" -or $choice -eq "n") {
    # Code to execute if the answer is no
    Write-Host "Operation canceled."
    # Add your code here
else {
    # Code to execute if the answer is neither yes nor no
    Write-Host "Invalid choice."
    # Add your code here, if needed

In this script, Read-Host is used to prompt the user for input. The user’s response is stored in the $choice variable. The script then uses if and elseif statements to check the value of $choice and executes different code blocks based on the answer.

You can replace the placeholders (# Add your code here) with your desired code that should be executed depending on the user’s choice.

Please note that this is a basic example, and you can modify it according to your specific requirements or expand it to include additional functionality as needed.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments