conanDrum
conanDrum

Reputation: 215

How to RESTART a specific command if it fails in Windows Powershell?

In a ps1 file I start 2 separate processes like so: As you can see the only difference is the CPU affinity.

$Process1 = Start-Process -FilePath 'C:\Windows\system32\notepad.exe' -PassThru
$Process1.ProcessorAffinity = 65535
$Process1.PriorityClass = 'RealTime'

$Process2 = Start-Process -FilePath 'C:\Windows\system32\notepad.exe' -PassThru
$Process2.ProcessorAffinity = 4294901760
$Process2.PriorityClass = 'RealTime'

Sometimes, randomly, one of the 2 processes fails with: Problem Event Name: BEX64

It is essential that the process is restarted immediately when a failure like this happens. So I am faced with this problem.

Can I monitor within the PS1 file the 2 processes and if one fails to restart it? The monitoring process must be able to distinguish which of the 2 processes has failed, so that the correct affinity is used to restart it.

If you have a solution involving windows batch script please visit How to RESTART a specific command if it fails in Windows Batch file?

Thanks

Upvotes: 0

Views: 520

Answers (1)

Doug Maurer
Doug Maurer

Reputation: 8868

$Process1 = Start-Process -FilePath 'C:\Windows\system32\notepad.exe' -PassThru
$Process1.ProcessorAffinity = 1
$Process1.PriorityClass = 'RealTime'
Write-Host Process ID $process1.Id started with CPU affinity $Process1.ProcessorAffinity

$Process2 = Start-Process -FilePath 'C:\Windows\system32\notepad.exe' -PassThru
$Process2.ProcessorAffinity = 2
$Process2.PriorityClass = 'RealTime'
Write-Host Process ID $process2.Id started with CPU affinity $Process2.ProcessorAffinity

while($true){
    foreach($process in $Process1,$Process2){
        if($process.hasexited){

            Write-Host "Process ID $($process.id) has exited, restarting."
            $priority = $process.PriorityClass
            $affinity = $process.ProcessorAffinity
            if($newprocess = $process.Start()){
                Write-Host Successfully restarted process ID $process.Id with CPU affinity $process.ProcessorAffinity
                $process.PriorityClass = $priority
                $process.ProcessorAffinity = $affinity
                Write-Host Priority Class set back to $process.PriorityClass
                Write-Host Process affinity set back to $process.ProcessorAffinity
            }
        }
    }
    Start-Sleep -Milliseconds 500
}

Upvotes: 3

Related Questions