2012-07-24 191 views
3

如何再次启动脚本?我有3个开关,我希望它们恢复到脚本的开头。Powershell按任意键退出

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保存到桌面上。”我希望它回去写主机部分。

回答

2

我个人最喜欢的检查用户输入是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) 

在我看来,这是一个非常独特的策略。我把这个从杰里·李·福特的书:微软的Windows PowerShell编程为绝对的初学者

你可以阅读更多关于这些和在PowerShell中所有其他环路位置:http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/

0

括在while (1) {}块整个事情。这就产生了一个无限循环如果遇到休息(结束循环)或退出(完脚本),将只终止。据推测,选项3将导致这些语句之一。

4

简单的,短的,愚蠢的:

& 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不退出脚本。