powershell: perpetual scripting restarting itself

I’ve been working for a while on a way to keep a perpetually running script on a server running, even though it does have a slow memory leak (not surprising since I don’t think scripts are meant to run forever). My previous attempts are ok, but leave some small issues on the table.

It might be easy to suggest just setting a Scheduled Task up. Well, yeah, that is easy, but it is my policy to not run Task Scheduler on servers unless absolutely necessary, and never on externally accessible servers.

As another alternative, I have decided to have the script that is infinitely running check its own memory use, respawn a new copy if the memory use is too high, and then kill itself. This is actually pretty easy once I started looking into it.

# spawn new process
$spawner = New-Object system.Diagnostics.ProcessStartInfo
$spawner.FileName = “powershell.exe”
$spawner.windowStyle =”Normal”
$spawner.Arguments = “-noexit -noprofile -command cd d:\path `; ./script.ps1”

# kill myself
Stop-Process $pid

The only fun trick here is $pid, which is an automatic variable that holds the ProcessID of the host Powershell.exe process. Also notice the two commands in the arguments section. I first change my directory (cd) over to a path. If I don’t do this, it starts in a default path. Then I start up my script like normal.

Checking memory is pretty simple as well.

$Process = Get-WmiObject win32_process | where {$_.ProcessID -match $pid}
$Memory = $Process.WorkingSetSize / 1024 / 1000 }