Git Product home page Git Product logo

plexbackup's Introduction

PlexBackup.ps1

PlexBackup.ps1 is a PowerShell script that can back up and restore Plex application data files on a Windows system. This document explains how it works and how to use it. If you don't care about the details and just want to get the instruction, see Getting Started.

Introduction

Plex does not offer a meaningful backup feature. Yes, it can back up a Plex database which can be handy in case of a Plex database corruption, but if you need to move your Plex instance to a different system or restore it after a hard drive crash, a single database backup will be of little use. For a meaningful backup, in addition to the Plex database, you will need a copy of the Plex Windows registry key and tens (or hundreds) of thousands of Plex application data files. Keep in mind that backing up gigabytes of data files may take a long time, especially when they are copied remotely, such as to a NAS share. And you must keep the Plex Media Server stopped while the backup job is running (otherwise, it can corrupt the data). In the other words, a meaningful Plex backup is a challenge to which I could not find a good solution, so I decided to build my own. Ladies and gentlemen, meet PlexBackup.ps1.

Overview

PlexBackup.ps1 (or, briefly, PlexBackup) is a PowerShell script that can back up and restore a Plex instance on a Windows system. The script backs up the Plex database, Windows registry key, and app data folders essential for the Plex operations (it ignores the non-essential files, such as logs or crash reports). And it makes sure that Plex is not running when the backup job is active (which may take hours). And it can send email to you, too.

IMPORTANT: The script will not back up media (video, audio, images) or Plex program files. You must use different backup techniques for those. For example, you can keep your media files on a RAID 5 disk array (for redundancy) and back them up to an alternative storage on a periodic basis. And you don't really need to back up Plex program files, since you can always download them. But for everything else, PlexBackup is your guy.

Backup types

The script can perform two types of backup: compressed (default or 7zip) and uncompressed (Robocopy).

Default

By default, the script compresses every essential folder under the root of the Plex application data folder (Plex Media Server) and saves the compressed data as separate ZIP files. For better efficiency (in case the backup folder is remote, such as on a NAS share), it first compresses the data in a temporary local file and then moves the compressed file to a backup folder (you can compress the data and save the ZIP files directly to the backup folder by setting the value of the TempDir parameter to null or empty string). There is a problem with PowerShell's compression routine that fails to process files and folders with paths that are longer than 260 characters. If you get this error, use the SpecialDirs parameter (in code or config file) to specify the folders that are too long (or parents of the subfolders or files that are too long) and PlexBackup will copy them as-is without using compression (by default, the following application data folder is not compressed: Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated).

7zip

Instead of the default compression, you can use the 7-zip command-line tool (7z.exe). 7-zip works faster (for both compression and extraction), it produces smaller compressed files, and it allowes you to exclude specific file types using the ExcludeFiles parameter (by default, it excludes *.bif, i.e. thumbnail preview files). To use 7-zip compression, install 7-zip, and set the PlexBackup script's Type parameter to 7zip (i.e. -Type 7zip) or use the -SevenZip shortcut (on command line). If you install 7-zip in a non-default directory, use the ArchiverPath parameter to set path to the 7z.exe file.

Robocopy

If you run PlexBackup with the Robocopy switch, instead of compression, the script will create a mirror of the Plex application data folder (minus the non-essential folders) using the Robocopy command (executed with the /MIR switch). Robocopy also allows you to exclude specific file types as described above.

You may want to play with either option to see which one works better for you.

Backup modes

PlexBackup can run in the following modes (specified by the Mode switch or a corresponding shortcut):

  • Backup: the default mode that creates a new backup archive.
  • Continue: resumes an incomplete backup job or, in case of the Robocopy backup, re-syncs the backup archive.
  • Restore: restores Plex application data from a backup.

If a previous backup does not exist, the Continue mode will behave just like the Backup mode. When running in the Continue mode for backup jobs that use compression, the script will skip the folders that already have the corresponding archive files. For the Robocopy backup, the Continue mode will synchronize the existing backup archive with the Plex application data files.

In all cases, before performing a backup or restore operation, PlexBackup will stop all Plex Windows services along with the Plex Media Server process. After the script completes the operation, it will restart them. You can use the NoRestart switch to tell the script not to restart the Plex Media Server process. The script will not run if the Plex Media Server is not active. To execute the script when Plex Media Server is not running, use the Inactive switch, but make sure you know what you are doing.

Plex Windows Registry key

To make sure PlexBackup saves and restores the right registry key, run it under the same account as Plex Media Server runs. The registry key will be backed up every time a backup job runs. If the backup folder does not contain the backup registry key file, the Plex registry key will not be imported on a restore.

Script execution

You must launch PlexBackup as Administrator while being logged in under the same account your Plex Media Server runs.

If you haven't done this already, you may need to adjust the PowerShell script execution policy to allow scripts to run. To check the current execution policy, run the following command from the PowerShell prompt:

Get-ExecutionPolicy

If the execution policy does not allow running scripts, do the following:

  • Start Windows PowerShell with the "Run as Administrator" option.
  • Run the following command:
Set-ExecutionPolicy RemoteSigned

This will allow running unsigned scripts that you write on your local computer and signed scripts downloaded from the Internet (okay, this is not a signed script, but if you copy it locally, make a non-destructive change--e.g. add a space character, remove the space character, and save the file--it should work).

Alternatively, you may want to run the script as:

start powershell.exe -noprofile -executionpolicy bypass -file .\PlexBackup.ps1 -ConfigFile .\PlexBackup.ps1.json

For additional information, see Running Scripts at Microsoft TechNet Library.

Dependencies

PlexBackup uses the following modules:

To verify that the modules get installed, run the script manually. You may be prompted to update the NuGet version (or you can do it yourself in advance).

Runtime parameters

The default values of the PlexBackup script's runtime parameters are defined in code, but you can override some of them via command-line arguments or config file settings.

Config file

Config file is optional. The default config file must be named after the PlexBackup script with the .json extension, such as PlexBackup.ps1.json. If the file with this name does not exist in the backup script's folder, PlexBackup will not care. You can also specify a custom config file name (or more accurately, path) via the ConfigFile command-line argument (see sample).

A config file must use JSON formatting, such as:

{
    "_meta": {
        "version": "1.0",
        "strict": false,
        "description": "Sample run-time settings for the PlexBackup.ps1 script."
    },
    "Mode": {
        "_meta": {
            "set": "Backup,Continue,Restore",
            "default": "Backup"
        },
        "value": null
    },
    "Type": {
        "_meta": {
            "set": ",7zip,Robocopy",
            "default": ""
        },
        "value": null
    },
    "PlexAppDataDir": {
        "_meta": {
            "default": "$env:LOCALAPPDATA\\Plex Media Server"
        },
        "value": null
    },
    "BackupRootDir": {
        "_meta": {
            "default": "$PSScriptRoot"
        },
        "value": null
    },
    "BackupDir": {
        "_meta": {
            "default": null
        },
        "value": null
    },
    "TempDir": {
        "_meta": {
            "default": "$env:TEMP"
        },
        "hasValue": true,
        "value": null
    },
    "WakeUpDir": {
        "_meta": {
            "default": null
        },
        "value": null
    },
    "ArchiverPath": {
        "_meta": {
            "default": "$env:ProgramFiles\\7-Zip\\7z.exe"
        },
        "value": null
    },
    "Quiet": {
        "value": null
    },
    "LogLevel": {
        "_meta": {
            "default": "None,Error,Warning,Info,Debug"
        },
        "value": null
    },
    "Log": {
        "value": true
    },
    "LogFile": {
        "value": null
    },
    "ErrorLog": {
        "value": null
    },
    "ErrorLogFile": {
        "value": null
    },
    "Keep": {
        "_meta": {
            "range": "0-[int]::MaxValue",
            "default": "3"
        },
        "value": null
    },
    "Retries": {
        "_meta": {
            "range": "0-[int]::MaxValue",
            "default": "5"
        },
        "value": null
    },
    "RetryWaitSec": {
        "_meta": {
            "range": "0-[int]::MaxValue",
            "default": "10"
        },
        "value": null
    },
    "RawOutput": {
        "value": null
    },
    "Inactive": {
        "value": null
    },
    "NoRestart": {
        "value": null
    },
    "NoSingleton": {
        "value": null
    },
    "NoVersion": {
        "value": null
    },
    "NoLogo": {
        "value": null
    },
    "Test": {
        "value": false
    },
    "SendMail": {
        "_meta": {
            "set": "Never,Always,OnError,OnSuccess,OnBackup,OnBackupError,OnBackupSuccess,OnRestore,OnRestoreError,OnRestoreSuccess",
            "default": "Never"
        },
        "value": null
    },
    "SmtpServer": {
        "value": "smtp.gmail.com"
    },
    "Port": {
        "_meta": {
            "range": "0-[int]::MaxValue",
            "default": "0"
        },
        "value": 587
    },
    "From": {
        "value": null
    },
    "To": {
        "value": null
    },
    "NoSsl": {
        "value": null
    },
    "CredentialFile": {
        "value": null
    },
    "NoCredential": {
        "value": null
    },
    "Anonymous": {
        "value": null
    },
    "SendLogFile": {
        "_meta": {
            "set": "Never,OnError,OnSuccess,Always",
            "default": "Never"
        },
        "value": "OnError"
    },
    "Logoff": {
        "value": null
    },
    "Reboot": {
        "value": null
    },
    "ForceReboot": {
        "value": null
    },
    "ExcludeDirs": {
        "_meta": {
            "default": ["Diagnostics","Crash Reports","Updates","Logs"]
        },
        "value": null
    },
    "ExcludeFiles": {
        "_meta": {
            "default": ["*.bif"]
        },
        "value": null
    },
    "SpecialDirs": {
        "_meta": {
            "default": ["Plug-in Support\\Data\\com.plexapp.system\\DataItems\\Deactivated"]
        },
        "value": null
    },
    "PlexServiceName": {
        "_meta": {
            "default": "^Plex"
        },
        "hasValue": false,
        "value": null
    },
    "PlexServerFileName": {
        "_meta": {
            "default": "Plex Media Server.exe"
        },
        "value": null
    },
    "PlexServerPath": {
        "value": null
    },
    "ArchiverOptionsCompress": {
        "_meta": {
            "comment": "The default options will always be applied. To include additional options, define them as an array.",
            "default": ["-r","-y"]
        },
        "value": null
    },
    "ArchiverOptionsExpand": {
        "_meta": {
            "comment": "The default options will always be applied. To include additional options, define them as an array.",
            "default":  ["-aoa","-y"]
        },
        "value": null
    },
    "Machine": {
        "_meta": {
            "set": "x86,amd64",
            "default": null
        },
        "value": null
    }
}

The root _meta element describes the file and the file structure. It does not include any configuration settings. The important attributes of the _meta element are:

  • version: can be used to handle future file schema changes, and
  • strictMode: when set to true every config setting that needs to be used must have the hasValue attribute set to true; if the strictMode element is missing or if its value is set to false, every config setting that gets validated by the PowerShell's if statement will be used.

The _meta elements under the configuration settings can contain anything (they are not processed at run time). In the sample config file, they contain default values, value ranges and other helpful information, but they can be removed if not needed.

Notice that to have the script recognize a null or empty value from the config file, you need to set the hasValue flags to true; otherwise, it will be ignored.

Make sure you use proper JSON formatting (escape characters, etc) when defining the config values. In particular you need to escape backslash characters, so if your backup root folder is located on a NAS share, such as \\MYNAS\Backups\Plex, the configuration file setting must look like:

    "BackupRootDir": {
        "_meta": {
            "default": "$PSScriptRoot"
        },
        "value": "\\\\MYNAS\\Backups\\Plex"
    },

Logging

Use the Log switch to write operation progress and informational messages to a log file. By default, the log file will be created in the backup folder. The default log file name reflects the name of the script with the .log extension, such as PlexBackup.ps1.log. The default log file is created in the backup folder. You can specify a custom log file path via the LogFile argument.

If you set the ErrorLog (or the ErrorLogFile) switch, the script will write error messages to a dedicated error log file (in addition to the standard log file, if one is defined). By default, the error log file will be created in the backup folder. The default error log file name reflects the name of the script with the .err.log extension, such as PlexBackup.ps1.err.log.

You can control log output sung the LogLevel and Quiet switches. The default log level is Info, but it can be also set to None, Error, Warning, and Debug. When the Quiet switch is set, no log messages will be written to the console.

You can control other log settings via the PlexBackup.ps1.StreamLogging.json configuration file (find out more at StreamLogging page), but unless you know what you are doing, you should probably leave it alone.

Debugging

In case you need to troubleshoot issues with PlexBackup, run the script with the Verbose flag, which will display additional information about the script processing. You can also set the Debug flag that will make the script print the information about the function calls. Keep in mind that the verbose and debug messages are only printed to the console and will not be saved in the log file.

Backup snapshots

Every time you run a new backup job, the script will create a backup snapshot folder. The name of the folder will reflect the timestamp of when the script started. Use the Keep switch to specify how many backup snapshots you want to keep: 0 (keep all previously created backups), 1 (keep the current backup snapshot only), 2 (keep the current backup snapshot and one before it), 3 (keep the current backup snapshot and two most recent snapshots), and so on. The default value is 3.

Backup version

When backing up data, PlexBackup records the version of Plex Media Server. If you try to restore a backup on a system with a different version of Plex Media Server, the operation will fail. To to force the operation over a version mismatch, use the NoVersion parameter, but be aware that it may pose risks. Keep in mind that if you execute PlexBackup with the Plex Media Server process not running, version information will not be saved or checked during the backup or restore operations.

Email notification

Use the SendMail parameter to let PlexBackup know whether or when you want to receive email notifications about the backup job completion using one of the following values:

  • Never: email notification will not be sent (default)
  • Always: email notification will be sent always
  • OnError: receive a notification if an error occurs during any operation
  • OnSuccess: receive a notification only if an operation was successful
  • OnBackup: receive a notification about a new or resumed backup operation on error or success
  • OnBackupError: receive notification about a new or resumed backup operations on error only
  • OnBackupSuccess: receive a notifications about a new or resumed backup operations on success only
  • OnRestore: receive a notification about a restore operation on error or success
  • OnRestoreError: receive a notification about a failed restore operation only
  • OnRestoreSuccess: receive a notifications about a failed restore operation only

To receive a copy of the log file along with the email notification, set the SendLogFile parameter to:

  • Never: the log file will not be sent as an email message attachment (default)
  • Always: the log file will be sent always
  • OnError: only send the log file if an error occurs
  • OnSuccess: only send the log file if no error occurs

SMTP server

When sending email notifications, Plex backup will need to know how to connect to the SMTP server. You can specify the server via the SmtpServer parameter, such as: -SmtpServer smtp.gmail.com . If the server is using a non-default SMTP port, use the Port parameter to specify the port, such as; -Port 587. If you do not want your message to be sent over encrypted (SSL) channel, set the NoSsl switch.

SMTP credentials

If your SMTP server does not require explicit authentication, use the Anonymous switch to tell PlexBackup to ignore explicit credentials; otherwise, the script will prompt you for credentials and save them in . If you want these credentials saved in a file (with password encrypted using the computer- and user-specific key) so you do not need to enter them every time the script runs, use the SaveCredentials switch. You can specify the path to the credential file via the CredentialFile parameters but if you don't, the script will try to use the default file named after the running script with the .xml extension, such as PlexBackup.ps1.xml. You can also generate the credential file in advance by running the following PowerShell command:

Get-Credential | Export-CliXml -Path "PathToFile.xml"

IMPORTANT: Most public providers, such as Gmail, Yahoo, Hotmail, and so on, have special requirements that you need to meet before you can use their SMTP servers to send email. For example, to use Gmail's SMTP server, you need to do the following:

(a) If you have two-factor authentication or, as Google calls it two-step verification, enabled, you cannot use your own password, so you need to generate an application password and use it along with your Gmail email address (see Sign in using App Passwords).

(b) If you are not using two-factor authentication, you can use your own password, but may need to enable less secure application access in your account settings (see Let less secure apps access your account).

For additional information or if you run into any issues, check support articles covering your provider.

Addresses

By default, PlexBackup will use the username provided via the SMTP credentials as both the To and From addresses, but you can set them explicitly via the To and From parameters. If the To parameter is not specified, the recipient's address will be the same as the sender's.

See also

Syntax

.\PlexBackup.ps1 `
    [[-Mode <String>] | -Backup | -Continue | -Update | -Restore] `
    [[-Type <String>] | -SevenZip | -Robocopy ] `
    [-ModuleDir <String>] `
    [-ConfigFile <String>] `
    [-PlexAppDataDir <String>] `
    [-BackupRootDir <String>] `
    [-BackupDir <String>] `
    [-TempDir <String>] `
    [-WakeUpDir <String>] `
    [-ArchiverPath <String>] `
    [-Quiet | -Q] `
    [-LogLevel <String>] `
    [-Log | -L] `
    [-LogFile <String>] `
    [-ErrorLog] `
    [-ErrorLogFile <String>] `
    [-Keep <Int32>] `
    [-Retries <Int32>] `
    [-RetryWaitSec <Int32>] `
    [-RawOutput]`
    [-Inactive] `
    [-NoRestart] `
    [-NoSingleton] `
    [-NoVersion] `
    [-NoLogo] `
    [-Test] `
    [-SendMail <String>] `
    [-SmtpServer <String>] `
    [-Port <Int32>] `
    [-From <String>] `
    [-To <String>] `
    [-NoSsl] `
    [-CredentialFile <String>] `
    [-SaveCredential] `
    [-Anonymous] `
    [-SendLogFile <String>] `
    [-ModulePath <String>] `
    [-Logoff] `
    [-Reboot] `
    [-ForceReboot] `
    [-Machine <String>] `
    [<CommonParameters>]

Arguments

Mode

Specifies the mode of operation:

  • Backup (default)
  • Continue
  • Restore

Backup

Shortcut for -Mode Backup.

Continue

Shortcut for -Mode Continue.

Restore

Shortcut for -Mode Restore.

Type

Specifies the non-default type of backup method:

  • 7zip
  • Robocopy

By default, the script will use the built-in compression.

SevenZip

Shortcut for -Type 7zip.

Robocopy

Shortcut for -Type Robocopy.

ModuleDir

Optional path to directory holding the modules used by this script. This can be useful if the script runs on the system with no or restricted access to the Internet. By default, the module path will point to the Modules folder in the script's folder.

ConfigFile

Path to the optional custom config file. The default config file is named after the script with the .json extension, such as 'PlexBackup.ps1.json'.

PlexAppDataDir

Location of the Plex Media Server application data folder.

BackupRootDir

Path to the root backup folder holding timestamped backup subfolders. If not specified, the script folder will be used.

BackupDirPath

When running the script in the Restore mode, holds path to the backup folder (by default, the subfolder with the most recent timestamp in the name located in the backup root folder will be used).

TempDir

Temp folder used to stage the archiving job (use local drive for efficiency). To bypass the staging step, set this parameter to null or empty string.

WakeUpDir

Optional path to a remote share that may need to be woken up before starting Plex Media Server.

ArchiverPath

Defines the path to the 7-zip command line tool (7z.exe) which is required when running the script with the -Type 7zip or -SevenZip switch. Default: $env:ProgramFiles\7-Zip\7z.exe.

Quiet

Set this switch to suppress log entries sent to a console.

LogLevel

Specifies the log level of the output:

  • None
  • Error
  • Warning
  • Info
  • Debug

Log

When set to true, informational messages will be written to a log file. The default log file will be created in the backup folder and will be named after this script with the .log extension, such as PlexBackup.ps1.log.

LogFile

Use this switch to specify a custom log file location. When this parameter is set to a non-null and non-empty value, the -Log switch can be omitted.

ErrorLog

When set to true, error messages will be written to an error log file. The default error log file will be created in the backup folder and will be named after this script with the .err.log extension, such as PlexBackup.ps1.err.log.

ErrorLogFile

Use this switch to specify a custom error log file location. When this parameter is set to a non-null and non-empty value, the -ErrorLog switch can be omitted.

Keep

Number of old backups to keep: 0 - retain all previously created backups, 1 - latest backup only, 2 - latest and one before it, 3 - latest and two before it, and so on.

Retries

The number of retries on failed copy operations (corresponds to the Robocopy /R switch).

RetryWaitSec

Specifies the wait time between retries in seconds (corresponds to the Robocopy /W switch).

RawOutput

Set this switch to display raw output from the external commands, such as Robocopy or 7-zip.

Inactive

When set, allows the script to continue if Plex Media Server is not running.

NoRestart

Set this switch to not start the Plex Media Server process at the end of the operation (could be handy for restores, so you can double check that all is good before launching Plex media Server).

NoSingleton

Set this switch to ignore check for multiple script instances running concurrently.

NoVersion

Forces restore to ignore version mismatch between the current version of Plex Media Server and the version of Plex Media Server active during backup.

NoLogo

Specify this command-line switch to not print version and copyright info.

Test

When turned on, the script will not generate backup files or restore Plex app data from the backup files.

SendMail

Indicates in which case the script must send an email notification about the result of the operation:

  • Never (default)
  • Always
  • OnError (for any operation)
  • OnSuccess (for any operation)
  • OnBackup (for both the Backup and Continue modes on either error or success)
  • OnBackupError
  • OnBackupSuccess
  • OnRestore (on either error or success)
  • OnRestoreError
  • OnRestoreSuccess

SmtpServer

Defines the SMTP server host. If not specified, the notification will not be sent.

Port

Specifies an alternative port on the SMTP server. Default: 0 (zero, i.e. default port 25 will be used).

From

Specifies the email address when email notification sender. If this value is not provided, the username from the credentails saved in the credentials file or entered at the credentials prompt will be used. If the From address cannot be determined, the notification will not be sent.

To

Specifies the email address of the email recipient. If this value is not provided, the addressed defined in the To parameter will be used.

NoSsl

Tells the script not to use the Secure Sockets Layer (SSL) protocol when connecting to the SMTP server. By default, SSL is used.

CredentialFile

Path to the file holding username and encrypted password of the account that has permission to send mail via the SMTP server. You can generate the file via the following PowerShell command:

Get-Credential | Export-CliXml -Path "PathToFile.xml"

The default log file will be created in the backup folder and will be named after this script with the '.xml' extension, such as 'PlexBackup.ps1.xml'.

SaveCredential

When set, the SMTP credentials will be saved in a file (encrypted with user- and machine-specific key) for future use.

Anonymous

Tells the script to not use credentials when sending email notifications.

SendLogFile

Indicates in which case the script must send an attachment along with th email notification:

  • Never (default)
  • Always
  • OnError
  • OnSuccess

Logoff

Specify this command-line switch to log off all user accounts (except the running one) before starting Plex Media Server. This may help address issues with remote drive mappings under the wrong credentials.

Reboot

Reboots the computer after a successful backup operation (ignored on restore).

ForceReboot

Forces an immediate restart of the computer after a successfull backup operation (ignored on restore).

Machine

Provided for rare cases when the backup script fails to re-launch Plex Media Server due to error 87: The parameter is incorrect. If you run into this problem (which is most likely due to a bad OS patch), set the machine flag to one of the following:

  • x86
  • amd64

Keep in mind that the machine flag should match the architecture of the Plex Media Server executable (not the operating system), so for a 32-bit process, use the x86 flag, and for the 64-bit use the amd64 flag. If you are not sure which pone to use, try one and if it does not work, try the other.

<CommonParameters>

Common PowerShell parameters (the script is not using these explicitly).

Returns

To check whether the backup script executed successfully or encountered an error, check the value of the $LASTEXITCODE variable:

  • 0 (zero) indicates success
  • 1 indicates error

Examples

The following examples assume that the the default settings are used for the unspecified script arguments.

Example 1

.\PlexBackup.ps1

Backs up Plex application data to the default backup location using the default Windows compression.

Example 2

.\PlexBackup.ps1 -ConfigFile "C:\Scripts\PlexBackup.ps1.ROBOCOPY.json

Runs the script with the non-default settings specified in the custom config file.

Example 3

.\PlexBackup.ps1 -Log -ErrorLog -Keep 5

Backs up Plex application data to the default backup location using file and folder compression. Writes progress to the default log file. Writes error messages to the default error log file. Keeps current and four previous backup snapshots (total of five).

Example 4

.\PlexBackup.ps1 -Type Robocopy
.\PlexBackup.ps1 -Robocopy

Creates a mirror copy of the Plex application data (minus the non-essential folders) in the default backup location using the Robocopy command.

Example 5

.\PlexBackup.ps1 -Type 7zip
.\PlexBackup.ps1 -SevenZip

Backs up Plex application data to the default backup location using the 7-zip command-line tool.

Example 6

.\PlexBackup.ps1 -BackupRootDir "\\MYNAS\Backup\Plex"

Backs up Plex application data to the specified backup location on a network share using file and folder compression.

Example 7

.\PlexBackup.ps1 -Mode Continue
.\PlexBackup.ps1 -Continue

Continues the last backup process (using file and folder compression) where it left off.

Example 8

.\PlexBackup.ps1 -Continue -Robocopy

Reruns the last backup process using a mirror copy.

Example 9

.\PlexBackup.ps1 -Mode Restore
.\PlexBackup.ps1 -Restore

Restores Plex application data from the latest backup from the default folder holding compressed data.

Example 10

.\PlexBackup.ps1 -Restore -Robocopy

Restores Plex application data from the latest backup in the default folder holding a mirror copy of the Plex application data folder.

Example 11

.\PlexBackup.ps1 -Mode Restore -BackupDirPath "\\MYNAS\PlexBackup\20190101183015"

Restores Plex application data from the specified backup folder holding compressed data on a remote share.

Example 12

.\PlexBackup.ps1 -SendMail Always -SaveCredential -SendLogFile OnError -SmtpServer smtp.gmail.com -Port 587

Runs a backup job and sends an email notification over an SSL channel. If the backup operation fails, the log file will be attached to the email message. The sender's and the recipient's email addresses will determined from the username of the credential object. The credential object will be set either from the credential file or, if the file does not exist, via a user prompt (in the latter case, the credential object will be saved in the credential file with password encrypted using a user- and computer-specific key).

Example 13

Get-Help .\PlexBackup.ps1

Shows help information.

plexbackup's People

Contributors

alekdavis avatar alekdavisintel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plexbackup's Issues

confused about TempZipFileDir

If this is in the config file ( PlexBackup.ps1.json ) :

    "TempZipFileDir": {
        "hasValue": true,
        "value": null

then does the compression staging happen in windows TEMP folder ?

7zip and Scheduled Plex backup

Hello,

I want to use 7zip with a Scheduled Plex backup.

If I understand, I need to edit PlexBackup.ps1.json like this ?

"Type": {
"_meta": {
"set": ",7zip,Robocopy",
"default": "7zip"
},
"value": null
},

Thank you

Feature request : Update backup

First of all : this might very well be the most elegantly written powershell script I've ever come across, personally or work-related.
Huge thumbs-up to @alekdavis !!

Being only human, we're never satisfied 🤦‍♂️
I took a backup yesterday, it took a looong time :

Script ran for (hr:min:sec.msec):
  02:54:49.962

The BackupRootDir was set to a local drive, so that wasn't the cause of the duration.
The size of the Plex folders is at cause.

TL;DR : would you consider adding an option to make a differential or incremental backup?
Perhaps the -update parameter to Compress-Archive might be useful ?

error on Win8 machine

reporting this even though it should have no future impact, and it is a marginal usage case..
Setting up backup on a family member's windows 8.1 machine, I got this error :

Compress-Archive : The term 'Compress-Archive' is not recognized as the name of a cmdlet, function, script file, or 
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try 
again.
At C:\users\edited\Downloads\PlexBackup-master\PlexBackup.ps1:2259 char:17
+                 Compress-Archive -DestinationPath $zipFilePath -Update
+                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Compress-Archive:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The error is pretty obvious, and the core reason is certainly the not-updated W8 OS.
Since I'll be using Robocopy, this is of no further consequence to me.
Perhaps some more elegant way of intercepting the missing Compress-Archive function is worth investigating...?

Folders unavailable after Plex server restart (WIN10 Home)

Hi Alek,
Backup script works just fine but after a (successful) restart of Plex Server instance, all remote folders located on a Synology NAS mapped drives, content is showing as unavailable. Manual restart of Plex solve the issue. Strange because the scheduled task is configured to run as the (only) account on the Win10 Home server as described in your help section. The Plex Server was first configured to run with the unique Microsoft account, I changed to run as local account but same issue.
Thank you, Francisco

Access to the cloud file is denied

hi,

i am having my backup folder on my OneDrive folder which is set to always keep offline, however after restoring my backup to a new machine, i starting getting the below error

C:\Users\xxxx\OneDrive\AppsBackups\Plex\20201115061503
Deleting old backup folder(s):
20201011061003
Access to the cloud file is denied
20201004061003
Access to the cloud file is denied
20200927061003
Access to the cloud file is denied
20200913061003
Access to the cloud file is denied
20200906061003

the end of the log seems to be running fine and successfully

Starting Plex Media Server process:
C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe
Script ended at:
2020.11.15 06:38:43.020
Script ran for (hr:min:sec.msec):
00:23:39.415
Script returned:
SUCCESS
Done.

[not an issue] Thank you very much !

Hello !

I wanted to thank you for all the work you have done.

I was looking on Google for a viable solution to back up Plex but results may vary. I don't want to loose 5 years of datas.

I was able to save the database in 30 mins, thank you !

More "readable" folder name ?

Hello,

Is it possible to change the name of the folder to a something like this "29-12-2019_15-15-29" ?

I didn't found any option in the config file. Thank you ! :D

Restore Operation Taking Ages

@alekdavis thank you for this amazing tool! When I get more time to play around with it I will definitely try to contribute!

I'm in the middle of a PMS migration from one Win10 Desktop (Source) to a net new one running Win10 as well (Destination). PMS on both systems are the same version and both systems have 7-Zip installed.

I placed the Backup Dir for the Source as a NAS in the config file then ported the config file over to the Destination system with zero changes.

I then proceeded to run .\PlexBackup.ps1 -Restore and it starts all well and good but then hangs for ages on unpacking the Codec 7z Archive. Have you seen this before? How long does a restore normally take?

Full Log:

PS C:\Users\USERNAME\Documents\GitHub\PlexBackup> .\PlexBackup.ps1 -Restore                                                PlexBackup v1.7.0 (c) 2020 Alek Davis                                                                                   Script started at:                                                                                                        06/24/2020 16:09:41
Validating log file folder:
  \\NAS\NASPlexMedia\PlexPowershellBackups\20200624150406
Operation mode:
  RESTORE
Backup type:
  7ZIP
Log file:
  \\NAS\NASPlexMedia\PlexPowershellBackups\20200624150406\Restore.log
Error log file:
  \\NAS\NASPlexMedia\PlexPowershellBackups\20200624150406\Restore.err.log
Plex Media Server version (CURRENT):
  1.19.4.2935
Plex Media Server version (BACKUP):
  1.19.4.2935
Stopping Plex Media Server process:
  Plex Media Server.exe
Restoring Plex app data folders from:
  \\NAS\NASPlexMedia\PlexPowershellBackups\20200624150406\2
Copying backup archive file:
  \\NAS\NASPlexMedia\PlexPowershellBackups\20200624150406\2\Codecs.7z
to a temp zip file:
  C:\Users\USERNAME\AppData\Local\Temp\PlexBackup-6e61f887-4e35-4509-a8da-55a4ecb701e5.7z
at:
  2020/06/24 16:09:47.368
Completed at:
  2020/06/24 16:09:51.859
Restoring Plex app data from:
  C:\Users\USERNAME\AppData\Local\Temp\PlexBackup-6e61f887-4e35-4509-a8da-55a4ecb701e5.7z
to Plex app data folder:
  C:\Users\USERNAME\AppData\Local\Plex Media Server\Codecs
at:
  2020/06/24 16:09:51.903

7z parameters for performance?

Is there a way your script could pass parameters to 7-zip to increase performance? I have a Plex system with 28 cores, 384GB of RAM, and NVME SSD storage - a backup operation currently uses ~5% CPU and about 5GB of RAM and takes about 90 mins to complete. It appears that 7z has some switches for memory usage and multithreading. Have you considered allowing usage of these parameters?

https://sevenzip.osdn.jp/chm/cmdline/switches/method.htm

Exclude folder don't work properly

Hi, i just started using your script
i've edited json config as follow
"ExcludeDirs": {
"_meta": {
"default": ["Diagnostics","Crash Reports","Updates","Logs","Cache"]
Basically "Cache" file is not needed as also stated by plex itself so i wanted to exclude it
adding Cache as you can see above

running this command as administrator in powershell...

PS C:\Users\manue\Downloads\PlexBackup-master\PlexBackup-master> .\PlexBackup.ps1 -Mode Backup -Type 7zip -LogLevel Debug -Log -ErrorLog -Keep 1

it keeps archive the cache folder

json and ps1 have the same name and are in the same folder

also, -loglevel debug don't show anything if i select -type 7zip
is it normal?
image

Initialization error.

Hi.
Just trying to get yr script going today.

I get this error on running it:

PlexBackup Init Error

I think my troubles may be a restriction caused by the user that runs PMS not being a local administrator and the need to run the ps1 script as an admin. May be?

unable to run PlexBackup

Hi, i am not good with powershell, so what i did it as follows:

  1. downloaded the files
  2. Right clicked on PlexBackup, Run with PowerShell
  3. got the following message
    Execution Policy Change
    The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
    you to the security risks described in the about_Execution_Policies help topic at
    https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
    [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A

i selected Y
the powershell immediately closes and even if i re-open it again, it keeps closing

also, how do i setup the location, do i need to do anything? or it will automatically make the folders in the same location?

EDIT: i think i managed to run it, i was doing it all wrong, now i got the following error, which i think cuz i did not set up the backup directory, which i really do it what to do with

PS C:\Users\MAIN\OneDrive\AppsBackups\Plex> .\PlexBackup.ps1
PlexBackup v1.7.2 (c) 2020 Alek Davis
Script started at:
07/25/2020 12:22:05
Cannot initialize run-time configuration settings.
PS C:\Users\MAIN\OneDrive\AppsBackups\Plex>

i would like all the backups to be stored in C:\Users\MAIN\OneDrive\AppsBackups\Plex (it is my onedrive folder)

Error: ZipArchiveHelper : Could not find a part of the path

Hello,

I keep getting the following error in the middle of the backup:
ZipArchiveHelper : Could not find a part of the path 'C:\Users\user\AppData\Local\Plex Media Server\Plex Media Server\Metadata\Albums\1\8f8f782d3066db7ea87a6b0573e065a1e2ad0e9.bundle\Contents\com.plexapp.agents.lyricfind\tracks\1fa14e37789fc5b5f6b5fa1fbfd0fe94eaec21ba\lyrics\c32a0f31a41aa2de43eb84799b25761a29af2d52'.

I can't figure it out.
Thank you.

Temp files not being deleted from Temp folder at end of process

Hi, first of all, THANK YOU for creating this tool. It's amazing and exactly what I needed. Can't thank you enough for sharing!

For the last month or so, I've noticed that the temporary files created in my Temp folder are not being deleted. So, they've started to accumulate and take up a huge amount of space on my drive. I just have to go in and manually delete them. My fear is I might forget to do this for an extended time and run out of disk space.

Any idea why this would be happening and how I could fix it?

Backup error due to missing registery key

I keep getting this error message:

reg : ERROR: The system was unable to find the specified registry key or value.
At D:\Backup\PlexBackup\PlexBackup.ps1:3115 char:13

I've looked in regedit the following key doesn't exist:

"HKU.DEFAULT\Software\Plex, Inc.\Plex Media Server

Is the key missing? And is there a way to remove this error?

Not able to run it at all...

So I've been backing up plex manually for ages, and ended up running across this and thought it'd be nice to be able to set this up and use it instead as it would be so much nicer/quicker to do this all automatically, but I'm running into issues right now.

First issue:
I'm trying to use the whole config file option ./PlexBackup.ps1 -ConfigFile "C:\Users\JourneyOver\Desktop\Projects\PlexBackup\PlexBackup.json", but each time I try to specify the config file location upon running the script it always seems to throw an error.

PlexBackup v1.3.3 (c) 2019 Alek Davis
Script started at:
  02/09/2019 22:09:22
Config file:
  C:\Users\JourneyOver\Desktop\Projects\PlexBackup\PlexBackup.json
not found.
Cannot initialize run-time configuration settings.

The thing is, is the file does exist so I do not know why it's throwing the error that it's not found..

I've tried moving everything to a different drive where all my other plex stuff is at and I end up running into a whole different issue as well...

D:\Plex Stuff\PlexBackup\PlexBackup.ps1 : Cannot validate argument on parameter 'Mode'. The argument "Stuff\PlexBackup\PlexBackup.json" does
not belong to the set "Backup,Continue,Restore" specified by the ValidateSet attribute. Supply an argument that is in the set and then try
the command again.
At line:1 char:38
+ ./PlexBackup.ps1 -ConfigFile D:\Plex Stuff\PlexBackup\PlexBackup.json
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [PlexBackup.ps1], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,PlexBackup.ps1

For some reason or another it seems to completely be cutting out the D:\Plex bit from the path, even though I surround it in quotes ./PlexBackup.ps1 -ConfigFile "D:\Plex Stuff\PlexBackup\PlexBackup.json"..

If I try without supplying a custom config file ./PlexBackup.ps1, it just ends up throwing a completely different error in the process..

PlexBackup v1.3.3 (c) 2019 Alek Davis
Script started at:
  02/09/2019 22:16:26
The variable cannot be validated because the value False is not a valid value for the SendMail variable.
At C:\Users\JourneyOver\Desktop\Projects\PlexBackup\PlexBackup.ps1:2685 char:9
+         $SendMail = $false
+         ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ValidateSetFailure

So I am at a complete loss on what the hell is going on with this script..Hopefully you can help out, since you are the one who made this script after all, and I'd really like to use it.

Scheduled backup fails

A backup that works fine when run interactively fails to run as a scheduled task. The email notification just says there was an error. There is no log folder or backup folder created. Most likely, it's due to NAS hosting the backup share being in the sleep mode.

What is SubDirFiles?

Quick question, but what is Sub Folder 1 (SubDirFiles) supposed to include? I just ran my first backup and noticed it was empty. I'm assuming it's looking for files in the root "Plex Media Server" folder as opposed to all the folders that get backed up in Sub Folder 2 (SubDirFolders), but am curious what those would typically be since I don't seem to have any.

Regardless, thank you for writing this awesome script! The Readme and code itself is wonderfully written and commented. Put my little script to shame!

Plex Update Service not automatically restarting

Running the script with command-line options interactively as follows:
.\PlexBackup.ps1 -Mode Backup -Type 7zip -PlexAppDataDir 'C:\Program Files (x86)\Plex\Plex Media Server' -BackupRootDir 'F:\Plex-Backup' -Log -ErrorLog -Verbose -Debug
Backup completes successfully, but the "Plex Update Service" does not automatically restart.

I'm 99.9% sure the issue is on line 1917 of PlexBackup.ps1 --
if ($services -and ($services.Count -le 0)) {
should instead read
if ($services -and ($services.Count -gt 0)) {

(In other words, if we stopped a service, the .Count should be >0, and thus we should enter the if and restart a service)

Editing that line as above and re-running the script restarts the Plex Update Service after execution correctly.

Exclude file types

Would be great to exclude file types, most notably .bif files (video preview thumbnails). If they are enabled, they are mingled in with the Media folder, and consume about 30GB of space on my system. They can be regenerated if needed by Plex.

Cannot save Plex Media Server version

Asked me to create a new issue for anything else that needed to be looked at and really the only thing left now that I can spot after you fixed the configfile stuff in 1.5.7 is the whole Plex media server version information not being able to be saved in a .txt file.

whenever I run the script when it gets to the saving of the Plex media server version information it always seems to end up outputting:

Plex Media Server version (CURRENT):
  1.15.6.1079
Cannot save Plex Media Server version:
  1.15.6.1079
to:
  H:\Ketarin\ketarin-files\installers\Backups\PMS\20190518114319\version.txt
Could not find a part of the path 'H:\Ketarin\ketarin-files\installers\Backups\PMS\20190518114319\version.txt'.

I dunno where exactly it's failing at in the script, but it seems to never make the version.txt file.

Plex doesn't start after backup

Hello,
First of all, great script, does all the backups properly with no problems, great job.

Now to my issue:
After the backup (using robocopy because incremental backups are fast) and script returned SUCCESS it tries to start PMS but "fails". The PMS icon appears in the notification area for a little sometimes during a minute or so, then closes i have to go in and restart it manually. Any ideas?

Also, is there a way to auto close the script on success? It stays running even after the backup has ended.

Thanks for your time.

Doesn't work with Powershell 6.2.3

When I run the backup using Powershell Core 6.2.3 I get the following error

LogException : The term 'Start-BitsTransfer' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At E:\MediaKitBackup\PlexBackup\PlexBackup.ps1:2275 char:17
+ LogException $_
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException

Backup.err.log

  • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,LogException

Cannot find Plex Media Server executable file

When running the script, I get the following error, but when running test path, it finds it.

PS C:\Users\Admin\Desktop\PlexBackup-master> .\PlexBackup.ps1
PlexBackup v1.5.10 (c) 2019 Alek Davis
Script started at:
  09/01/2019 09:15:19
Operation mode:
  BACKUP
Backup type:
  DEFAULT
Cannot find Plex Media Server executable file:
  C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe
PS C:\Users\Admin\Desktop\PlexBackup-master> Test-Path 'C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe'
True
PS C:\Users\Admin\Desktop\PlexBackup-master>

Allow 7-Zip Compression

Any thoughts on allowing the (optional?) use of 7zip as the compression method using the portable edition? In a few anecdotal tests, 7zip compressed my metadata folder in about 2/3 the time as the powershell compression currently used. It also resulted in a noticable-but-not-groundbreaking reduction in file size if that matters to others.

Restore Question

Hi Mr.Davis, sorry to reach you in this way

i’m running a plex server on a beelink sei8 mini pc, all is working fine except for BSOD like twice a month

Amazon.com: Beelink SEi8 Mini PC 8th Generation Intel i5-8279U Processor,(up to 4.1GHz) Windows 10 Pro Mini Computer with 8G DDR4 RAM/256GB M.2 NVME SSD,Supports 6MB Smart Cache,4K@30Hz Dual HDMI,WIFI6,BT5.0.: Computers & Accessories

with a plex lifetime pass

after many troubleshooting i found out i have a bad block on main ssd(disk c with os and plex files)
chkdsk state no problem on filesystem but there are 32kb of files on damaged sectors
no matter how many times i run chkdsk /f /r at boot

Damaged sector is on the primary boot partition on a first sight

even if i’m not completely sure the ssd is the problem, i have intention to replace it soon with another ssd nvme to exclude it’s the real problem.

Since the very beginning i’ve done backup with your script but never done a restore

The correct step to restore, just to be sure are:

Reinstall os from 0

-install everything i need other than plex and update os and driver, then:

i don’t know if i have first to download and install plex media server and login in or if i have first to restore plex files using the script with a command like this:

.\PlexBackup.ps1 -Mode Restore -BackupDirPath “\MYNAS\PlexBackup\20190101183015”

andf only after install plex media server and login again?

Which one is correct? It’s very important to me because i’ve very huge libraries, if i have to restart from 0 it’ll take 2 weeks at least working on it with 2 people

Obviously the media content drive will be placed in the same location as they were before, i mean drive letter and other stuff…
(Media content are something like 10 TB splitted on 4 external hdds WD, connected to mini pc by a powered HUB usb 3.0)

in restore mode i have to specify to use 7zip? if yes,which command i have to use?

Thanks for your answer

Best Regards

Skip Cache Folder

Plex's documentation (here) says that the cache folder can be skipped as it is simply regenerated the next time that Plex runs. Could the script skip backing up and/or restoring the Cache folder? It would save about 10 minutes of my backup time, and 6 gigs of storage for me.

PS - 7zip compression is terrific - did my first backup using that method today and it was great :-)

Restore Error

Hello,

I restored a backup, all seems ok but I had an error, sorry It's in French :
L'opération a réussi. => The operation is a success.

reg : L'opération a réussi.
Au caractère D:\PlexBackup-master\PlexBackup.ps1:2692 : 13
reg import $backupRegKeyFilePath *>&1 | Out-Null
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (L'opération a réussi.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

Is that bad ? Thank you

Exception calling "Write" with "3" argument(s): "Stream was too long."

PS C:\WINDOWS\system32> C:\PlexBackup-1.6.2\PlexBackup.ps1
PlexBackup v1.6.2 (c) 2019 Alek Davis
Script started at:
  03/14/2020 21:56:20
Operation mode:
  BACKUP
Backup type:
  DEFAULT
Plex Media Server version (CURRENT):
  1.18.8.2527
Stopping Plex service(s):
  Plex Update Service
Stopping Plex Media Server process:
  Plex Media Server.exe
Ignoring script parameter:
  ExcludePlexAppDataFiles
Backup will be saved in:
  C:\PlexBackup-1.6.2\20200314215620
Creating backup folder:
  C:\PlexBackup-1.6.2\20200314215620
Creating task-specific subfolder(s) in:
  C:\PlexBackup-1.6.2\20200314215620
Backing up special subfolders.
Moving folder:
  C:\Users\Blake\AppData\Local\Plex Media Server\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
to:
  C:\PlexBackup-1.6.2\20200314215620\3\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
at:
  2020/03/14 21:56:21.437
Completed at:
  2020/03/14 21:56:21.468
Backing up Plex app data folders from:
  C:\Users\Blake\AppData\Local\Plex Media Server
to:
  C:\PlexBackup-1.6.2\20200314215620\1
Archiving:
  C:\Users\Blake\AppData\Local\Plex Media Server\Cache
to temp file:
  C:\Users\Blake\AppData\Local\Temp\PlexBackup-6fdf4a99-c09f-4548-b21c-246276f21fb0.zip
at:
  2020/03/14 21:56:21.533
LogException : Exception calling "Write" with "3" argument(s): "Stream was too long."
At C:\PlexBackup-1.6.2\PlexBackup.ps1:2266 char:13
+             LogException $_
+             ~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,LogException
 
Restoring special subfolders.
Copying folder:
  C:\PlexBackup-1.6.2\20200314215620\3\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
to:
  C:\Users\Blake\AppData\Local\Plex Media Server\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
at:
  2020/03/14 22:24:41.475
Completed at:
  2020/03/14 22:24:41.572
Starting Plex service(s):
  Plex Update Service
Starting Plex Media Server process:
  C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe
Script ended at:
  2020/03/14 22:24:42.308
Script ran for (hr:min:sec.msec):
  00:28:21.911
Script returned:
  ERROR
Measure-Object : The property "Length" cannot be found in the input for any objects.
At C:\PlexBackup-1.6.2\PlexBackup.ps1:3522 char:55
+ ... ldItem -Recurse $BackupDirPath | Measure-Object -Property Length -Sum
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException
    + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand

Whenever I run the script with the default settings, I get this output. Please assist!

PS C:\WINDOWS\system32> Get-Host | Select-Object Version

Version      
-------      
5.1.18362.628

Log PMS version

It would be helpful to have the backup reflect the version of PMS at the time the backup was done. It would be even better if the backup version could be enforced during the restore operation.

Must issue a STARTTLS command first when sending email

I am able to send an email through Gmail with the less secure app turned on. When I try to send an email with 2 steps verification turned on, I receive the following error message.

image

I use the code generated by Gmail as my new password in my credentials.xml. It does not give me an error message about the credentials.

Error compressing Plex app data files. Error compressing folder 'Cache'. Exception calling "Write" with "3" argument(s): "Stream was too long." Stream was too long.

Hi there,

I have just installed the script and set everything up. On first backup run the backup seemed to finish really quick, so I went to the PlexBackup destination folder and opened the Backup.log. The script seems to have failed with the error of "Error compressing Plex app data files. Error compressing folder 'Cache'. Exception calling "Write" with "3" argument(s): "Stream was too long." Stream was too long."

I searched this on Google but didn't get any results.

My entire log is below, any ideas how to resolve this? Thanks

PlexBackup v2.0.6 (c) 2019-2021 Alek Davis
Script started at:
  09/08/2021 16:32:58
Operation mode:
  BACKUP
Backup type:
  DEFAULT
Plex version:
  1.24.2.5000
Log file:
  B:\PlexBackup\20210908163258\Backup.log
Stopping Plex services:
  Plex Update Service
Stopping Plex Media Server process:
  Plex Media Server.exe
Backup will be saved in:
  B:\PlexBackup\20210908163258
Creating task-specific subfolders in:
  B:\PlexBackup\20210908163258
    1
    2
    3
    4
Saving version:
  1.24.2.5000
to:
  B:\PlexBackup\20210908163258\Version.txt
Backing up special folders.
Moving:
  C:\Users\Chewie\AppData\Local\Plex Media Server\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
to:
  B:\PlexBackup\20210908163258\4\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
at:
  2021/09/08 16:33:02.604
Completed at:
  2021/09/08 16:33:02.700
Backing up Plex app data files in the root folder.
No files found in 'C:\Users\Chewie\AppData\Local\Plex Media Server' (it's okay).
Backing up Plex app data folders.
Archiving:
  C:\Users\Chewie\AppData\Local\Plex Media Server\Cache
to:
  B:\PlexBackup\20210908163258\2\Cache.zip
at:
  2021/09/08 16:33:03.210
Restoring special folders.
Copying:
  B:\PlexBackup\20210908163258\4\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
to:
  C:\Users\Chewie\AppData\Local\Plex Media Server\Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated
at:
  2021/09/08 16:39:42.219
Completed at:
  2021/09/08 16:39:42.274
Error compressing Plex app data files. Error compressing folder 'Cache'. Exception calling "Write" with "3" argument(s): "Stream was too long." Stream was too long.
Starting Plex services:
  Plex Update Service
Starting Plex Media Server:
  C:\Program Files (x86)\Plex\Plex Media Server\Plex Media Server.exe
Script ended at:
  09/08/2021 16:39:42
Script ran for (hr:min:sec.msec):
  00:06:43.795
Script execution result:
  ERROR
Done.

an error that I cant fix in the plex backup script (or config file)

Hi Alek

so I have tried to get your powershell script working to backup my plex db

When I execute the script, |I get an error

PS C:\plexbackupscripts> .\plexbackup.ps1
The "=" operator is missing after a named argument.
At C:\plexbackupscripts\PlexBackup.ps1:320 char:26

  • [Parameter(Mandatory, <<<<  ParameterSetName="ModeType")]
    
    • CategoryInfo : ParserError: (:) [], ParseException
    • FullyQualifiedErrorId : MissingEqualsInNamedArgument

the only thing I changed in the config file was to replace "null" in the backup dir with my backup location (which is pasted below) and is on the same drive as the backup script at c:\PlexBackupData"

Any help gratefully received

Thanks

{
"_meta": {
"version": "1.0",
"strict": false,
"description": "Sample run-time settings for the PlexBackup.ps1 script."
},
"Mode": {
"_meta": {
"set": "Backup,Continue,Restore",
"default": "Backup"
},
"value": null
},
"Type": {
"_meta": {
"set": ",7zip,Robocopy",
"default": ""
},
"value": null
},
"PlexAppDataDir": {
"_meta": {
"default": "$env:LOCALAPPDATA\Plex Media Server"
},
"value": null
},
"BackupRootDir": {
"_meta": {
"default": "$PSScriptRoot"
},
"value": "\BackupPlex"
},
"BackupDir": {
"_meta": {
"default": null
},
"value": null
},
"TempDir": {
"_meta": {
"default": "$env:TEMP"
},
"hasValue": true,
"value": null
},
"WakeUpDir": {
"_meta": {
"default": null
},
"value": null
},
"ArchiverPath": {
"_meta": {
"default": "$env:ProgramFiles\7-Zip\7z.exe"
},
"value": null
},
"Quiet": {
"value": null
},
"LogLevel": {
"_meta": {
"default": "None,Error,Warning,Info,Debug"
},
"value": null
},
"Log": {
"value": true
},
"LogFile": {
"value": null
},
"ErrorLog": {
"value": null
},
"ErrorLogFile": {
"value": null
},
"Keep": {
"_meta": {
"range": "0-[int]::MaxValue",
"default": "3"
},
"value": null
},
"Retries": {
"_meta": {
"range": "0-[int]::MaxValue",
"default": "5"
},
"value": null
},
"RetryWaitSec": {
"_meta": {
"range": "0-[int]::MaxValue",
"default": "10"
},
"value": null
},
"RawOutput": {
"value": null
},
"Inactive": {
"value": null
},
"NoRestart": {
"value": null
},
"NoSingleton": {
"value": null
},
"NoVersion": {
"value": null
},
"NoLogo": {
"value": null
},
"Test": {
"value": false
},
"SendMail": {
"_meta": {
"set": "Never,Always,OnError,OnSuccess,OnBackup,OnBackupError,OnBackupSuccess,OnRestore,OnRestoreError,OnRestoreSuccess",
"default": "Never"
},
"value": null
},
"SmtpServer": {
"value": "smtp.gmail.com"
},
"Port": {
"_meta": {
"range": "0-[int]::MaxValue",
"default": "0"
},
"value": 587
},
"From": {
"value": null
},
"To": {
"value": null
},
"NoSsl": {
"value": null
},
"CredentialFile": {
"value": null
},
"NoCredential": {
"value": null
},
"Anonymous": {
"value": null
},
"SendLogFile": {
"_meta": {
"set": "Never,OnError,OnSuccess,Always",
"default": "Never"
},
"value": "OnError"
},
"Logoff": {
"value": null
},
"Reboot": {
"value": null
},
"ForceReboot": {
"value": null
},
"ExcludeDirs": {
"_meta": {
"default": ["Diagnostics","Crash Reports","Updates","Logs"]
},
"value": null
},
"ExcludeFiles": {
"_meta": {
"default": ["*.bif"]
},
"value": null
},
"SpecialDirs": {
"_meta": {
"default": ["Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated"]
},
"value": null
},
"PlexServiceName": {
"_meta": {
"default": "^Plex"
},
"hasValue": false,
"value": null
},
"PlexServerFileName": {
"_meta": {
"default": "Plex Media Server.exe"
},
"value": null
},
"PlexServerPath": {
"value": null
},
"ArchiverOptionsCompress": {
"_meta": {
"comment": "The default options will always be applied. To include additional options, define them as an array.",
"default": ["-r","-y"]
},
"value": null
},
"ArchiverOptionsExpand": {
"_meta": {
"comment": "The default options will always be applied. To include additional options, define them as an array.",
"default": ["-aoa","-y"]
},
"value": null
}
}

One Occurrence of "retrun" Causes Error

I chose to remove the option to not compress special folders and encountered an error:

WriteDebug "Entered BackupSpecialFolders."

if (!($specialDirs) -or
     ($specialDirs.Count -eq 0)) {
    **retrun** $true
}

Set-ExecutionPolicy RemoteSigned is not recommended

Instead you can simply run as admin a .cmd file with the following line in it :

start powershell.exe -noprofile -executionpolicy bypass -file .\PlexBackup.ps1 -ConfigFile ".\PlexBackup.ps1.json"

This way you don't permanantly change security settings on you system.

Also you can adapt the following function to your code in order to require admin when the script start

Function RequireAdmin {
	If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
		Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $PSCommandArgs" -Verb RunAs
		Exit
	}
}

Script won't backup .bif files when using a 7-zip back up even when I remove .bif from the excluded files in the config file

Hi,

First let me say thanks for creating this script. It's been very useful. I'm running it the following way:

.\PlexBackup.ps1 -SevenZip -NoRestart -Log -ErrorLog -Keep 1

And in the config file I made the following edit:

"ExcludeFiles": {
        "_meta": {
            "default": ["*.bif"]
        },
        "value": [""]

I was hoping that was enough for the bif files to be included in the backup but after examining the backups I see they are not. Perhaps I'm doing something wrong? The config file basically the example config file with that modification.

I'm attaching the config file as well. (I had to change it from .json to .txt so it would let me attach it)

PlexBackup.ps1.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.