Clean up old Plex Media files older than 7 days off server every day

A macos script that removes any old plex media files with (.ts) file type older than 7 days from a user Teddy’s desktop folder “Plex Media” and /Users/Teddy/Movies folder

To create a macOS script that removes .ts files older than 7 days from the “Plex Media” folder on the user Teddy’s desktop and the /Users/Teddy/Movies folder, you can use a bash script. Open Terminal and use a text editor like nano to create the script:

Copy code
nano remove_old_plex_files.sh
Copy and paste the following script into the text editor:

Copy code – Link: https://gist.github.com/patent-ed/70af956fc1f064fdcfc4f628f8c93b6b.js
[gist]70af956fc1f064fdcfc4f628f8c93b6b[/gist]
Save the file by pressing Ctrl + X, then Y, and hit Enter.

Now, you need to make the script executable. In the Terminal, run:

bash
Copy code
chmod +x remove_old_plex_files.sh
To run the script, simply execute the following command in Terminal:

Copy code
./remove_old_plex_files.sh
This script will search for .ts files older than 7 days in the specified folders and remove them.

Next we will automate this process by a launchd to schedule the script to run at a specific interval; in this case 1x a day.

To set up the existing script to run once every day and empty the trash, you can use launchd. Here are the steps to create a launchd plist file and configure it to run the script daily:

Move the script to a suitable location (e.g., /usr/local/bin). Open Terminal and execute the following command:

Copy code
sudo mv remove_old_plex_files.sh /usr/local/bin

Create a new plist file for launchd. Use a text editor like nano to create the file:

Copy code
nano ~/Library/LaunchAgents/com.user.remove_old_plex_files.plist
Copy and paste the following plist content into the text editor:

Copy code
Copy code – Link: https://gist.github.com/patent-ed/70af956fc1f064fdcfc4f628f8c93b6b.js
[gist]53715a971e554775d97f081a59e4dbc7[/gist]

This plist file is configured to run the script daily at 1:00 AM. You can change the Hour and Minute values to your desired time.

Save the file by pressing Ctrl + X, then Y, and hit Enter.

Load the plist file into launchd:

Copy code
launchctl load ~/Library/LaunchAgents/com.user.remove_old_plex_files.plist
Update the script to empty the trash. Open the script using nano:

Copy code
sudo nano /usr/local/bin/remove_old_plex_files.sh

Verify code is present at the following line at the end of the script to empty the trash:
osascript -e 'tell application "Finder" to empty the trash'
Save the file by pressing Ctrl + X, then Y, and hit Enter.

The script will now run daily at the specified time and remove old Plex media files as well as empty the trash.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Share via
Copy link