次の方法で共有


PowerShell Examples: Guess the number

This blog is part of a series that shows example PowerShell code for those learning the language.

This time we’re using PowerShell create a simple game where you need to guess a number.

This example explores basic loops, logical operations (like –ne, –ge, –lt) and entering data with Read-Host.

 

## Guess the number# [int] $Number = (Get-Random 100) + 1[int] $Guess = 0 Write-Host "I'm thinking of a number between 1 and 100." While ($Number -ne $Guess) {     Write-Host -NoNewline "What is the number? " $Guess = [int] (Read-Host)     If ($Guess -gt $Number) { Write-Host "$Guess is too high." } If ($Guess -lt $Number) { Write-Host "$Guess is too low." }    }Write-Host "Correct! $Number is the number I was thinking!"

 

In case you were wondering what the output would look like, here it is:

 

I'm thinking of a number between 1 and 100.
What is the number? 50
50 is too high.
What is the number? 25
25 is too high.
What is the number? 12
12 is too low.
What is the number? 19
19 is too high.
What is the number? 15
15 is too high.
What is the number? 13
Correct! 13 is the number I was thinking!