2012-07-24 187 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不退出腳本。