Powershell - 循环脚本,直到用户选择退出

时间:2012-07-24 18:45:55

标签: powershell powershell-v2.0

如何重新启动脚本?我有3个开关,我希望它们恢复到脚本的开头。

Import-Module ActiveDirectory
Write-Host "--Please Login using a.account--"
#login
$credential = Get-Credential
#Main
Write-Host "--Remote Computer Rename v2.0--"
Write-Host "1. Query AD (Outputs to a text file)"
Write-Host "2. Quick computer rename"
Write-host "3. Quit"
$choice=Read-Host "Chose a number to continue"

#AD Query for computer
switch ($choice)
{
 1 {
Write-Host "--Enter first five characters of computer name or full computer name i.e.     USCLT--"
$cn=Read-Host 'Computer name'
$out="$cn*"
Get-ADComputer -Filter 'SamAccountName -like $out' >> c:\myscripts\dsquery.txt
Write-Host "Query complete.  See dsquery.txt saved to Desktop."
}

...rest of my code.

所以在之后看到保存到桌面的dsquery.txt。“我希望它回到写主机部分。

4 个答案:

答案 0 :(得分:5)

简单,简短,愚蠢:

& cmd /c pause
exit

这甚至会提供TO请求的“按任意键”消息。如果您希望继续使用PowerShell:

Read-Host "Press any key to exit..."
exit

但我们也可能会收到回复:

$reply = Read-Host "Please type EXIT to exit"
if ($reply -eq "EXIT") { exit; }

我喜欢Read-Host在输入Ctrl-C时退出脚本,就像cmd的pause那样。

答案 1 :(得分:3)

我个人最喜欢检查用户输入的是do { } until ()循环。这是你的代码添加了循环,这将完成你想要的:

Import-Module ActiveDirectory
Write-Host "--Please Login using a.account--"
#login
$credential = Get-Credential
#Main
do {
Write-Host "--Remote Computer Rename v2.0--"
Write-Host "1. Query AD (Outputs to a text file)"
Write-Host "2. Quick computer rename"
Write-host "3. Quit"
$choice=Read-Host "Chose a number to continue"

#AD Query for computer
switch ($choice)
{
 1 {
Write-Host "--Enter first five characters of computer name or full computer name i.e.     USCLT--"
$cn=Read-Host 'Computer name'
$out="$cn*"
Get-ADComputer -Filter 'SamAccountName -like $out' >> c:\myscripts\dsquery.txt
Write-Host "Query complete.  See dsquery.txt saved to Desktop."
}

...rest of my code.
} until ($choice -eq 3)

在我看来,这是一个非常独特的策略。我从Jerry Lee Ford的书中得到了这个:绝对初学者的Microsoft Windows PowerShell编程

您可以在这里阅读有关powershell中的这些和所有其他循环的更多信息:http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/

答案 2 :(得分:0)

将整个事件包含在while (1) {}块中。这会创建一个无限循环,只有在遇到中断(结束循环)或退出(结束脚本)时才会终止。据推测,选项3将导致其中一个陈述。

答案 3 :(得分:0)

blog post中我发现:

echo "Press any key to exit..."
$Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | OUT-NULL
$Host.UI.RawUI.FlushInputbuffer()