Staying alive

Jan 20, 2021

Okay so sometimes I just need to have a bunch of processes run in paralel on a VM. Especially flaky processes that tend to want to crash, but you want to keep them alive regardless. Instead of fiddling with multithreading and async awaits, I just want to scale a process and let the OS handle it for me.

I use this little nugget:

#Asks for a path and a pool size
param( [Parameter(Mandatory=$true)] $ProcessPath, $PoolCount = 1) 

#Gets an automated processname. if you start "C:/dev/Process.exe", it will look for "Process"
$ProcessName =[System.IO.Path]::GetFileNameWithoutExtension($ProcessPath)   


#Count the number of known instances of the process
function Number-Instances([string]$process)
{
    @(get-process -ea silentlycontinue $process).count
}


#And keeps them alive, slowly building them up
do
{
    Write-Output -InputObject 'Checking process pool...'
    $ProcessCount = Number-Instances $ProcessName
    Write-Output -InputObject ('{0}/{1} processes alive' -f $ProcessCount, $PoolCount)
    if ( $ProcessCount -lt $PoolCount )
    {
        Write-Output -InputObject ('Starting a new ' -f $ProcessCount, $PoolCount)
        Start-Process -FilePath $ProcessPath
    }
    Start-Sleep -Seconds 5
}
until ($False)

If anything crashes, the script fills up the pool.

Is it dumb? Yeah, but often you just need to scale a thing.

powershell
Creative

Yasen Dinkov

Killing every damn service in the room