Powershell - 循环脚本,直到用户选择退出 [英] Powershell - Loop script until user chooses to exit
问题描述
我怎样才能重新开始一个脚本?我有 3 个开关,我希望它们恢复到脚本的开头.
How can I start a script over again? I have 3 switches and I want them to revert back to the beginning of the script.
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 之后."我希望它返回到写入主机部分.
So after See dsquery.txt saved to Desktop." I want it to go back to write-host portion.
推荐答案
我个人最喜欢检查用户输入的是 do { } until ()
循环.这是添加了循环的代码,这将完成您要查找的内容:
My personal favorite for checking user input is the do { } until ()
loop. Here is your code with the added loop, this will accomplish what your looking for:
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 编程
This is a pretty unique strategy in my opinion. I took this from Jerry Lee Ford’s book : Microsoft Windows PowerShell Programming for the absolute beginner
您可以在此处阅读有关 powershell 中这些和所有其他循环的更多信息:http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/
you can read more about these and every other loop in powershell here : http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/
这篇关于Powershell - 循环脚本,直到用户选择退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!