This PowerShell script is a simple number guessing game. The script generates a random number between 1 and 100, and the user has to guess the correct number.
-
Open PowerShell: To run the game, open a PowerShell terminal or PowerShell ISE on your computer.
-
Run the Script: Copy and paste the provided PowerShell code into your PowerShell terminal or script editor.
-
Start Guessing: After running the script, you will see the message "Guess a number between 1 and 100:". The game will then prompt you to enter your first guess.
-
Make a Guess: Enter a number between 1 and 100 and press Enter. The script will let you know if your guess is higher or lower than the random number.
-
Continue Guessing: Keep guessing until you find the correct number. The script will give you feedback on each guess, indicating if the number is higher or lower than the random number.
-
Win Condition: When you guess the correct number, the script will display a congratulatory message in green color along with the number of attempts it took you to find the correct number.
## How the Script Works
-
Generate a Random Number: The script starts by using the
Get-Randomcmdlet to generate a random number between 1 and 100. This random number is stored in the variable$random. -
Initialize Variables: Two additional variables are initialized:
$guess: This variable will store the user's current guess.$numberOfGuesses: This variable will keep track of the number of attempts the user has made.
-
Game Loop: The script uses a
whileloop to repeatedly prompt the user for their guess until they guess the correct number. The loop continues as long as the user's guess is not equal to the random number ($guess -ne $random). -
Get User's Guess: Inside the loop, the script uses the
Read-Hostcmdlet to prompt the user to enter their guess. The entered value is stored in the$guessvariable. -
Compare the Guess: The script then compares the user's guess with the random number using
ifandelseifstatements.- If the guess is greater than the random number, the script displays "Your guess is higher than the number." in red color.
- If the guess is lower than the random number, the script displays "Your guess is lower than the number." in blue color.
-
Repeat or Exit: The loop continues until the user guesses the correct number, at which point the loop condition becomes false, and the script exits the loop.
-
Winning Message: After the loop, the script displays a congratulatory message in green color, indicating the random number and the number of attempts it took to find the correct number.