• Login
  • Register
  • Login Register
    Login
    Username/Email:
    Password:
    Or login with a social network below
  • Forum
  • Website
  • GitHub
  • Status
  • Translation
  • Features
  • Team
  • Rules
  • Help
  • Feeds
User Links
  • Login
  • Register
  • Login Register
    Login
    Username/Email:
    Password:
    Or login with a social network below

    Useful Links Forum Website GitHub Status Translation Features Team Rules Help Feeds
    Jellyfin Forum Support General Questions Stopping & Starting processes in Windows

     
    • 0 Vote(s) - 0 Average

    Stopping & Starting processes in Windows

    fivergj
    Offline

    Junior Member

    Posts: 2
    Threads: 1
    Joined: 2025 May
    Reputation: 0
    Country:United Kingdom
    #1
    2025-05-15, 03:54 PM
    Hi, I'm quite new to Jellyfin, I have had everything up and running for a few weeks on a windows11 and now I wanted to automate the backup.

    I created a powershell script to stop the jellyfin.server process and do the backup and then restart the process, but I was finding that on restart accessing jellyfin via the usual url failed to connect to the server.

    I found that exiting via the Jellyfin system tray icon and then starting the Jellyfin Tray App fixed the problem so I assumed I needed to also stop and start the Jellyfin.Window.Tray process. The processes are stopping and starting but I cannot get it to work without manually restarting the tray.

    I also tried with just the Jellyfin.Window.Tray process which appeared to affect both processes but that also required a manual restart.

    What is the correct order in which to stop and start the two processes (Jellyfin.Server & Jellyfin.Window.Tray)? Or is there another process that needs to be stopped/started?

    Many thanks
    fivergj
    Offline

    Junior Member

    Posts: 2
    Threads: 1
    Joined: 2025 May
    Reputation: 0
    Country:United Kingdom
    #2
    2025-05-24, 08:51 PM
    Well I think I've managed to work it out, so posting here what I've done in case it helps someone else :-)

    If backing up manually:
    Right click the Jellyfin system tray icon > exit
    Backup the config & data folders
    From Windows start menu > Jellyfin Tray App

    If scripting in powershell:
    Stop the Jellyfin.Windows.Tray
    Stop the Jellyfin process (confusingly named jellyfin.server in task manager)
    Backup the config & data folders
    Start process pointing at the Jellyfin.Windows.Tray.exe

    N.B.
    To get Start-Process to work properly I found it necessary to include "-WorkingDirectory" and not use "-WindowStyle Hidden".
    To get the script to run from Task Scheduler I had to have it executed by the same user who is logged in when kicking it off manually.
    Any existing front end connections to Jellyfin will stop working, you just need to close the page and reopen a new one. 

    If you want to go the whole hog here is the script I (and Gemini) wrote:

    #####################################################################################################################################
    #Requires -version 5.0
    # Script to stop Jellyfin, backup config and data and restart Jellyfin.
    # Script must be run by the same user as runs Jellyfin
    # Any existing connections to the front end will have to be restarted manually

    # --- Configuration ---
    $JellyfinProcessName = "Jellyfin"
    $JellyfinTrayProcessName = "Jellyfin.Windows.Tray"
    $JellyfinConfigPath = "C:\ProgramData\Jellyfin\Server\config"
    $JellyfinDataPath = "C:\ProgramData\Jellyfin\Server\data"
    $JellyfinExePath = "C:\Program Files\Jellyfin\Server\jellyfin.exe"
    $JellyfinTrayExePath = "C:\Program Files\Jellyfin\Server\jellyfin-windows-tray\Jellyfin.Windows.Tray.exe"
    $JellyfinTrayWrkDir = "C:\Program Files\Jellyfin\Server"
    $BackupBaseDir = "Y:\Jellyfin_Backup"
    $LogBaseDir = "C:\Program Files\Powershell Scripts\Jellyfin Backup\Logs"
    $LogFileNamePrefix = "Jellyfin_backup"
    $LogRetentionDays = 7
    $ZippedLogRetentionMonths = 3


    # --- Helper Function for Logging ---
    function Write-Log {
        param(
            [Parameter(Mandatory=$true)]
            [string]$LogMessage
        )
        $CurrentDate = Get-Date -Format "yyyyMMdd"
        $CurrentTime = Get-Date -Format "HH:mm:ss"
        $LogFilePath = Join-Path -Path $LogBaseDir -ChildPath ($LogFileNamePrefix + "_" + $CurrentDate + ".log")
        $LogEntry = "[$CurrentDate $CurrentTime] $LogMessage"
        Add-Content -Path $LogFilePath -Value $LogEntry
        Write-Host $LogEntry # Also display in console
    }

    # --- Helper Function for Zipping Files ---
    function Compress-Files {
        param(
            [Parameter(Mandatory=$true)]
            [string[]]$SourcePaths,
            [Parameter(Mandatory=$true)]
            [string]$DestinationPath
        )
        try {
            Compress-Archive -Path $SourcePaths -DestinationPath $DestinationPath -Force -ErrorAction Stop
            Write-Log "Successfully created archive: '$DestinationPath'"
            return $true
        }
        catch {
            Write-Error "Failed to create archive '$DestinationPath'. Error: $($_.Exception.Message)"
            Write-Log "Error creating archive '$DestinationPath': $($_.Exception.Message)"
            return $false
        }
    }

    # --- Log Management Functions ---
    function Archive-OldLogs {
        Write-Log "Starting log archiving process..."
        $CutoffDate = (Get-Date).AddDays(-$LogRetentionDays).Date
        $LogFilesToArchive = Get-ChildItem -Path $LogBaseDir -Filter "$LogFileNamePrefix_*.log" |
            Where-Object {$_.LastWriteTime.Date -lt $CutoffDate}

        if ($LogFilesToArchive) {
            $CurrentMonthYear = Get-Date -Format "yyyyMM"
            $ArchiveFileName = ($LogFileNamePrefix + "_archive_" + $CurrentMonthYear + ".zip")
            $ArchiveFilePath = Join-Path -Path $LogBaseDir -ChildPath $ArchiveFileName
            $FilesToZip = $LogFilesToArchive.FullName

            if ($FilesToZip) {
                Write-Log "Archiving $($FilesToZip.Count) log files to '$ArchiveFilePath'..."
                if (Compress-Files -SourcePaths $FilesToZip -DestinationPath $ArchiveFilePath) {
                    foreach ($LogFile in $LogFilesToArchive) {
                        try {
                            Remove-Item -Path $LogFile.FullName -Force -ErrorAction Stop
                            Write-Log "Deleted archived log file: '$($LogFile.FullName)'"
                        }
                        catch {
                            Write-Warning "Failed to delete archived log file '$($LogFile.FullName)'. Error: $($_.Exception.Message)"
                            Write-Log "Error deleting archived log file '$($LogFile.FullName)': $($_.Exception.Message)"
                        }
                    }
                }
            } else {
                Write-Log "No log files older than $($LogRetentionDays) days found for archiving."
            }
        } else {
            Write-Log "No log files found to archive."
        }
    }

    function Remove-OldArchives {
        Write-Log "Starting old archive removal process..."
        $CutoffDate = (Get-Date).AddMonths(-$ZippedLogRetentionMonths)
        $OldArchives = Get-ChildItem -Path $LogBaseDir -Filter "$($LogFileNamePrefix)_archive_*.zip" | Where-Object {$_.LastWriteTime -lt $CutoffDate}

        if ($OldArchives) {
            Write-Log "Found $($OldArchives.Count) old log archives to remove."
            foreach ($Archive in $OldArchives) {
                try {
                    Remove-Item -Path $Archive.FullName -Force -ErrorAction Stop
                    Write-Log "Deleted old log archive: '$($Archive.FullName)'"
                }
                catch {
                    Write-Warning "Failed to delete old log archive '$($Archive.FullName)'. Error: $($_.Exception.Message)"
                    Write-Log "Error deleting old log archive '$($Archive.FullName)': $($_.Exception.Message)"
                }
            }
        } else {
            Write-Log "No old log archives found for removal."
        }
    }

    # --- Function to Restart Jellyfin ---
    function Restart-Jellyfin {
        Write-Log "Attempting to restart Jellyfin due to a script failure..."
        if (Test-Path -Path $JellyfinTrayExePath -PathType Leaf) {
            try {
                Start-Process -FilePath $JellyfinTrayExePath -WorkingDirectory $JellyfinTrayWrkDir -ErrorAction Stop
                Write-Log "'$JellyfinTrayExePath' started successfully after a script failure."
            }
            catch {
                Write-Error "Failed to start '$JellyfinTrayExePath' after a script failure. Error: $($_.Exception.Message)"
                Write-Log "Failed to start '$JellyfinTrayExePath' after a script failure. Error: $($_.Exception.Message)"
            }
        }
        else {
            Write-Error "Jellyfin executable not found at '$JellyfinTrayExePath'. Cannot restart Jellyfin."
            Write-Log "Jellyfin executable not found at '$JellyfinTrayExePath'. Cannot restart Jellyfin."
        }
    }

    # --- Trap for Terminating Errors ---
    trap {
        Write-Error "A terminating error occurred: $($_.Exception.Message)"
        Write-Log "A terminating error occurred: $($_.Exception.Message)"
        Restart-Jellyfin
        exit 1 # Exit the script after attempting to restart
    }


    # --- Script Start ---
    ########################################################
    Write-Log "Starting Jellyfin backup script..."


    # 0. Manage existing logs
    ############################
    Archive-OldLogs
    Remove-OldArchives


    # 1a. Terminate the Jellyfin Tray process first
    ############################
    Write-Log "Attempting to terminate the '$JellyfinTrayProcessName' process..."
    try {
        Get-Process -Name $JellyfinTrayProcessName -ErrorAction Stop | Stop-Process -Force -ErrorAction Stop
        Write-Log "'$JellyfinTrayProcessName' process terminated successfully."
    }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
        Write-Log "'$JellyfinTrayProcessName' process was not found or already stopped."
    }
    catch {
        Write-Warning "An unexpected error occurred while trying to stop '$JellyfinTrayProcessName': $($_.Exception.Message)"
        Write-Log "Error stopping '$JellyfinTrayProcessName': $($_.Exception.Message)"
        # We don't necessarily want to restart Jellyfin if it just failed to stop.
        # The subsequent start process should handle this.
    }

    # Add a small delay to ensure the process has fully terminated and released file locks
    Start-Sleep -Seconds 5


    # 1b. Terminate the Jellyfin Server process second
    ############################
    Write-Log "Attempting to terminate the '$JellyfinProcessName' process..."
    try {
        Get-Process -Name $JellyfinProcessName -ErrorAction Stop | Stop-Process -Force -ErrorAction Stop
        Write-Log "'$JellyfinProcessName' process terminated successfully."
    }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
        Write-Log "'$JellyfinProcessName' process was not found or already stopped."
    }
    catch {
        Write-Warning "An unexpected error occurred while trying to stop '$JellyfinProcessName': $($_.Exception.Message)"
        Write-Log "Error stopping '$JellyfinProcessName': $($_.Exception.Message)"
        # We don't necessarily want to restart Jellyfin if it just failed to stop.
        # The subsequent start process should handle this.
    }

    # Add a small delay to ensure the process has fully terminated and released file locks
    Start-Sleep -Seconds 5


    # 2. Create the backup directory if it doesn't exist
    ############################
    Write-Log "Checking if backup directory '$BackupBaseDir' exists..."
    if (-not (Test-Path -Path $BackupBaseDir -PathType Container)) {
        Write-Log "Backup directory '$BackupBaseDir' not found. Creating it..."
        try {
            New-Item -ItemType Directory -Path $BackupBaseDir -Force -ErrorAction Stop | Out-Null
            Write-Log "Backup directory '$BackupBaseDir' created successfully."
        }
        catch {
            Write-Error "Failed to create backup directory '$BackupBaseDir'. Error: $($_.Exception.Message)"
            Write-Log "Failed to create backup directory '$BackupBaseDir'. Error: $($_.Exception.Message)"
            Write-Log "Please ensure the drive Y: is accessible and you have write permissions."
            # A failure here is critical, let the trap handle restart if needed.
            throw # Re-throw the error to trigger the trap
        }
    } else {
        Write-Log "Backup directory '$BackupBaseDir' already exists."
    }


    # 3. Create the log directory if it doesn't exist
    ############################
    Write-Log "Checking if log directory '$LogBaseDir' exists..."
    if (-not (Test-Path -Path $LogBaseDir -PathType Container)) {
        Write-Log "Log directory '$LogBaseDir' not found. Creating it..."
        try {
            New-Item -ItemType Directory -Path $LogBaseDir -Force -ErrorAction Stop | Out-Null
            Write-Log "Log directory '$LogBaseDir' created successfully."
        }
        catch {
            Write-Error "Failed to create log directory '$LogBaseDir'. Error: $($_.Exception.Message)"
            Write-Log "Failed to create log directory '$LogBaseDir'. Error: $($_.Exception.Message)"
            Write-Log "Please ensure you have permissions to create directories in '$LogBaseDir'."
            # A failure here might not be critical enough to restart Jellyfin immediately.
            # The script might still be able to proceed with backup and restart.
        }
    } else {
        Write-Log "Log directory '$LogBaseDir' already exists."
    }


    # 4. Zip the folders
    ############################
    $CurrentDate = Get-Date -Format "yyyyMMdd"
    $BackupFileName = "jellyfin_backup_$($CurrentDate).zip"
    $BackupFilePath = Join-Path -Path $BackupBaseDir -ChildPath $BackupFileName

    Write-Log "Creating backup archive: '$BackupFilePath'..."


    # Check if source folders exist
    ############################
    if (-not (Test-Path -Path $JellyfinConfigPath -PathType Container)) {
        Write-Error "Jellyfin config path '$JellyfinConfigPath' not found. Aborting backup."
        Write-Log "Jellyfin config path '$JellyfinConfigPath' not found. Aborting backup."
        # A failure here is critical for backup, let the trap handle restart.
        throw
    }
    if (-not (Test-Path -Path $JellyfinDataPath -PathType Container)) {
        Write-Error "Jellyfin data path '$JellyfinDataPath' not found. Aborting backup."
        Write-Log "Jellyfin data path '$JellyfinDataPath' not found. Aborting backup."
        # A failure here is critical for backup, let the trap handle restart.
        throw
    }

    try {
        Compress-Archive -Path $JellyfinConfigPath, $JellyfinDataPath -DestinationPath $BackupFilePath -Force -ErrorAction Stop
        Write-Log "Backup created successfully: '$BackupFilePath'"
    }
    catch {
        Write-Error "Failed to create backup archive. Error: $($_.Exception.Message)"
        Write-Log "Failed to create backup archive. Error: $($_.Exception.Message)"
        # Backup failure might not necessitate a Jellyfin restart.
    }

    # 5. Start Jellyfin
    ############################
    Write-Log "Attempting to start '$JellyfinTrayExePath'..."
    if (Test-Path -Path $JellyfinTrayExePath -PathType Leaf) {
        try {
    #        Start-Process -FilePath $JellyfinExePath -WindowStyle Hidden -ErrorAction Stop
            Start-Process -FilePath $JellyfinTrayExePath -WorkingDirectory $JellyfinTrayWrkDir -ErrorAction Stop
            Write-Log "'$JellyfinTrayExePath' started successfully."
        }
        catch {
            Write-Error "Failed to start '$JellyfinTrayExePath'. Error: $($_.Exception.Message)"
            Write-Log "Failed to start '$JellyfinTrayExePath'. Error: $($_.Exception.Message)"
            # If starting Jellyfin fails, the trap will have already run if a terminating error occurred earlier.
            # We don't want to get into a potential infinite restart loop here.
        }
    }
    else {
        Write-Error "Jellyfin executable not found at '$JellyfinTrayExePath'. Cannot start Jellyfin."
        Write-Log "Jellyfin executable not found at '$JellyfinTrayExePath'. Cannot start Jellyfin."
    }




    Write-Log "Script finished."
    « Next Oldest | Next Newest »

    Users browsing this thread: 1 Guest(s)


    • View a Printable Version
    • Subscribe to this thread
    Forum Jump:

    Home · Team · Help · Contact
    © Designed by D&D - Powered by MyBB
    L


    Jellyfin

    The Free Software Media System

    Linear Mode
    Threaded Mode