4

我怎样才能重新开始一个脚本?我有 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

4 回答 4

7

简单、简短、愚蠢:

& 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 时退出脚本,就像 cmdpause一样。

于 2013-04-17T14:14:10.650 回答
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 Programming for the absolute 初学者

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

于 2012-07-24T19:09:54.853 回答
2

从我发现的一篇博文中:

echo "Press any key to exit..."
$Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | OUT-NULL
$Host.UI.RawUI.FlushInputbuffer()
于 2019-04-13T09:20:54.750 回答
0

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

于 2012-07-24T19:04:06.857 回答