Question:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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. |
So after See dsquery.txt saved to Desktop.” I want it to go back to write-host portion.
Answer:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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) |
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
you can read more about these and every other loop in powershell here : http://www.powershellpro.com/powershell-tutorial-introduction/logic-using-loops/