Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Loop script until user chooses to exit

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.

So after See dsquery.txt saved to Desktop." I want it to go back to write-host portion.

like image 511
Robert Avatar asked Dec 16 '22 21:12

Robert


1 Answers

Simple, short, stupid:

& cmd /c pause
exit

This will even contribute the "Press any key" message the TO requested. If you prefer to stay in PowerShell:

Read-Host "Press any key to exit..."
exit

But we may also get the input back:

$reply = Read-Host "Please type EXIT to exit"
if ($reply -eq "EXIT") { exit; }

I like that Read-Host exits the script when typing Ctrl-C, like cmd's pause does.

like image 73
Andreas Spindler Avatar answered Dec 31 '22 04:12

Andreas Spindler