X
Popular Searches

Setting a Windows Application to Run Indefinitely With PowerShell

Powershell logo

If you’re used to bash and new to PowerShell, even the simplest of tasks can be confusing. For all the Linux admins forced to use Windows Server, here’s how to set configure a program to run as an auto-restarting daemon.

While ($true), Start-Process

In PowerShell, you can loop like many programming and scripting languages. The syntax is while($true) followed by braces for the loop.

In this loop, we’re going to launch the process with Start-Process. This takes a -FilePath argument with a path to your executable. You can use relative pathing for this.

while($true) 
{ 
    Start-Process -FilePath .\StartServer.exe -Wait 
}

You will also need the -Wait parameter, because by default PowerShell will loop indefinitely and eat up all your RAM, disconnecting you from RDP and forcing a server restart. I found this out the hard way, so make sure it waits.

This will launch the process as its own window, with the PowerShell window running in the background. If the application experiences a crash, or shuts down, the PowerShell script will auto-restart it.

Advertisement

If being in its own window is a problem, you can try running with the -NoNewWindow parameter. This doesn’t handle stderr very well though, so you may want to try Invoke-Process, a custom function from the PowerShell Gallery.

In my case, I was running multiple of these windows, so I set the titles to be the directory name so I could tell them apart.

$host.ui.RawUI.WindowTitle = $(get-location)

Running At Startup

It wouldn’t be a daemon if a server restart screwed your whole operation, so you’ll need to configure this script to run at startup.

Luckily, this is fairly easy on Windows. Open up the Task Scheduler:

Create a new Basic Task:

Set it to run when the computer starts:

Select “Start a Program,” and browse to find your script. You can add arguments here as well.

And with that, you should be safe from restarts, and safe from random application crashes.

Anthony Heddings Anthony Heddings
Anthony Heddings is the resident cloud engineer for LifeSavvy Media, a technical writer, programmer, and an expert at Amazon's AWS platform. He's written hundreds of articles for How-To Geek and CloudSavvy IT that have been read millions of times. Read Full Bio »

The above article may contain affiliate links, which help support CloudSavvy IT.