Plex Media Server: Auto-Restart Recovery PowerShell Script

The following PowerShell script does the following:

  1. Collects information about the local Plex Media Server for remote connectivity.
  2. Using Remote Access settings, attempts to connect to the server detecting if the server is not responding.
  3. In the event the local Plex Media Server is not responding after a period of time and a number of attempts will stop the Plex Media Server and restart it.
  4. Will repeat as needed.

Notice: You will want to stop this script during Plex Media Server upgrades.

-Enjoy

$iLoop = $false
$Stoploop = $false
[int]$Retrycount = "0"

do {
    do {
        $PMS_LM = Get-ItemProperty -Path Registry::'HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Plex, Inc.\Plex Media Server'
        $PMS_CU = Get-ItemProperty -Path Registry::'HKEY_CURRENT_USER\Software\Plex, Inc.\Plex Media Server'

        try {            
            $MyPlex = (Invoke-RestMethod -Method Get -Uri "http://localhost:32400/myplex/account" -Headers @{'X-Plex-Token' = $PMS_CU.PlexOnlineToken; 'Accept' = 'application/json';}).MyPlex
            $uri = "https://$($MyPlex.publicAddress.Replace(".","-")).$($PMS_CU.CertificateUUID).plex.direct:$($MyPlex.publicPort)/?X-Plex-Token=$($PMS_CU.PlexOnlineToken)"
            Write-Host (Get-Date -Format g) : "Connecting to $uri"
            if((Invoke-WebRequest -Uri $Uri -TimeoutSec 10).StatusCode -eq 200) {

                $Stoploop = $true
                Start-Sleep -Seconds 30

            }
            else {

                if($Retrycount -gt 2) {
                    Write-Host "Restarting Plex"
                    Get-Process | Where-Object Path -Like "$($PMS_LM.InstallFolder)*" | Stop-Process -Force
                    Start-Process -FilePath "$($PMS_LM.InstallFolder)Plex Media Server.exe"
                    Start-Sleep -Seconds 60

                }
                else {
                    Write-Host "Retrying..."
                    Start-Sleep -Seconds 5
                    $Retrycount = $Retrycount + 1
                }
            }
        }
        catch {
            Write-Host "Failed to get response"
            if($Retrycount -gt 2) {
                Write-Host "Restarting Plex"
                Get-Process | Where-Object Path -Like "$($PMS_LM.InstallFolder)*" | Stop-Process -Force
                Start-Process -FilePath "$($PMS_LM.InstallFolder)Plex Media Server.exe"
                Start-Sleep -Seconds 60

            }
            else {
                Write-Host "Retrying..."
                Start-Sleep -Seconds 5
                $Retrycount = $Retrycount + 1
            }

        }

    }
    while ($Stoploop -eq $false)
}
while ($iLoop -eq $false)