I recently had an issue running a batch file using a UNC path and discovered that UNC paths are not always supported. This failed in the following line.
ForFiles /p "\\Server\folder\username\SQLBackups" /s /d -13 /c "cmd /c del /q @file"
The solution was to use PUSHD and POPD as shown here
:: Create a temporary drive letter mapped to your UNC root location
:: and effectively CD to that location
pushd \\Server\folder\username
:: Do your work
ForFiles /p "SQLBackups" /s /d -13 /c "cmd /c del /q @file"
:: Remove the temporary drive letter and return to your original location
popd
Explained here: windows - How to run batch file from network share without "UNC path are not supported" message? - Stack Overflow
Delete Files Older Than X Days with ForFiles Command
You can quickly delete files older than X days with ForFiles Command. Follow the given steps below to use CMD delete files older than x days:
Step 1. Left-click the Windows main menu and search for Command Prompt. Right-click the result and select the "Run as administrator" option.
Step 2. Type in ForFiles /p "C:\path\to\folder" /s /d -X /c "cmd /c del /q @file" to delete files on Windows that haven't been modified in the last X days and press Enter. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -X to select files with a last modified date.
ForFiles command breakdown
/p - indicates the pathname to start searching.
/s - instructs ForFiles to search inside subdirectories.
/d -specifies the last modified date for a file.
/c - instructs ForFiles to execute the command (must be wrapped in double quotes). The default is "cmd /c del @file".
/q -allows deleting folders without requiring confirmation.