PowerShell理解 - 功能如果退出

时间:2018-03-31 09:26:30

标签: powershell

我的工作场所负责自动化,需要让我的理论理解起来,所以我可以开始学习和编写脚本。

我在下面创建了一个简单的功能,提示用户输入一个国家/地区。如果国家输入错误3次,程序应退出。

我有2个理论/脚本理解问题

  1. 错误的国家/地区文字中的写入输出应显示倒计时3-2-1,然后退出。

  2. $count = 0 function game { do { $country = Read-Host "What is the best country in the world? " if ($country -eq "Australia") { $(win) } else { $count++ Write-Host "Wrong answer you have $count attempts remaining." Write-Host "Try again:" $(game) } } while ($count -le 3) } function win { Clear-Host Write-Host "You Win" } 不起作用。我假设我在这里做错了。

  3. 我可以帮助了解我出错的地方。我不是要求编码帮助,而是要求理论指针。我很少寻求帮助,并希望尽可能以某种方式偿还。

    {{1}}

1 个答案:

答案 0 :(得分:2)

如果你向后计数,你应该从计数3开始,然后递减而不是递增,在其他之后调用$count = 3 function game { while ($count -gt 0){ $count-- $country = Read-Host "What is the best country in the world? " if ($country -eq "Any") { $(win) break # stop the loop, we have correct answer } else { echo "Wrong answer you have $count attempts remaining" if ($count -ne 0){ echo "Try again: "} } } } function win { clear-host Write-host "You Win" } game # remember to call the first function to start the script ,不仅仅是再次提问,是创建递归,如果你想要使用递归,你不需要一个循环,这里有一个while循环的例子,并使用echo(我更喜欢* nix方式)。

> .\3-times.ps1
What is the best country in the world? : a
Wrong answer you have 2 attempts remaining
Try again:
What is the best country in the world? : b
Wrong answer you have 1 attempts remaining
Try again:
What is the best country in the world? : c
Wrong answer you have 0 attempts remaining

失败3次的示例输出:

function game {
    Param ([int]$max_attempts)
    if ($max_attempts -eq 0 ) # check we still have attempts
    { 
        Write-Output "You lost"
        return
    } else {
        Write-Output "You have $max_attempts attempts remaining"
        $country = Read-Host "What is the best country in the world? "
        if ($country -eq "Any") {
            $(win)
        } else {
            Write-Output "Wrong answer"
            $max_attempts-- # one attempt spent
            game($max_attempts)
        }
    }
}
function win {
    clear-host
    Write-host "You Win"
}
game(3) # start script

编辑:

以下是一个没有循环的递归方式的示例。

> .\3-times-recursive.ps1
You have 3 attempts remaining
What is the best country in the world? : a
Wrong answer
You have 2 attempts remaining
What is the best country in the world? : b
Wrong answer
You have 1 attempts remaining
What is the best country in the world? : c
Wrong answer
You lost

输出:

{{1}}