TankorSmash
TankorSmash

Reputation: 12747

How to repeat a command forever in Powershell?

I'm running a command that I want to rerun when it completes, without needing to navigate back to the terminal to enter the command again.

I know in Ubuntu, I can run a terminal with a command, and it'll loop forever if I have it set up right, something like gnome-terminal -x $MY_COMMAND.

Given that I can't mark Powershell to rerun the command instead of closing the window, how can I repeat a command indefinitely?

Upvotes: 13

Views: 41341

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

This will infinitely run a command repeatedly after execution completes:

while ($true) {
    Start-Process -FilePath python3 -ArgumentList .\manage.py, runserver_plus, 8080 -Wait -ErrorAction SilentlyContinue
}

Alternatively:

#requires -Version 3

while ($true) {
    try {
        $params = @{FilePath     = 'python3'
                    ArgumentList = '.\manage.py', 'runserver_plus', '8080'
                    Wait         = $true
                    ErrorAction  = 'Stop'}
        Start-Process @params
    } catch {
        <# Deal with errors #>
        continue
    }
}

Upvotes: 7

TankorSmash
TankorSmash

Reputation: 12747

Turns out the answer is fairly straight forward, wrap the command in a loop forever. This'll allow you to Ctrl-C out of it, and it'll keep repeating even after your command completes or otherwise exits the first time.

while ($true) {
  my_command;
}

Or in my case as a one liner: while ($true) { python3 .\manage.py runserver_plus 8080; }

Upvotes: 14

Related Questions