Submit a enquiry






    Back to all posts

    Move files into one root folder on desktop

    Guide
    by Andrew Tebbott Developer

    We were using WP All Import (which is a great plugin) to export/import blogs from one site to another.

    To reliably grab all the images, we download the /uploads/ folder, then add to WP ALL Imports uploads folder for the import to check if the image exists, before attempting to download it from an external source.

    To do this we needed to remove the usually /uploads/ year and month, and just dump all images into one folder. So instead of /uploads/2024/06/image-name.jpg we wanted /uploads/image-name.jpg – but there was 000’s of folders so a big task to manually move them all via drag/drop.

    So we made a Windows PowerShell script which we ran on our desktop and it did this instantly 🙂

    Feel free to use, the script is:

    # Set the path to your uploads folder
    $rootPath = "C:\path\to\your\files"
    
    # Get all files from all subdirectories within the uploads folder
    $files = Get-ChildItem -Path $rootPath -Recurse -File
    
    # Move each file to the root uploads folder
    foreach ($file in $files) {
        $destinationPath = Join-Path -Path $rootPath -ChildPath $file.Name
        Move-Item -Path $file.FullName -Destination $destinationPath -Force
    }
    
    # Remove all empty subdirectories within the uploads folder
    $directories = Get-ChildItem -Path $rootPath -Recurse -Directory | Sort-Object -Property FullName -Descending
    foreach ($dir in $directories) {
        if (-not (Get-ChildItem -Path $dir.FullName)) {
            Remove-Item -Path $dir.FullName -Force -Recurse
        }
    }

    The script does the following:

    • Sets the path to your uploads folder.
    • Recursively gets all files in the uploads folder and its subfolders.
    • Moves each file to the root uploads folder.
    • Removes all empty subdirectories within the uploads folder.

    Explanation:

    • Get-ChildItem -Path $rootPath -Recurse -File: Retrieves all files from the uploads folder and its subdirectories.
    • Move-Item -Path $file.FullName -Destination $destinationPath -Force: Moves each file to the root uploads folder.
    • Get-ChildItem -Path $rootPath -Recurse -Directory | Sort-Object -Property FullName -Descending: Retrieves all directories within the uploads folder and sorts them in descending order to ensure we remove empty subdirectories from the deepest level upwards.
    • Remove-Item -Path $dir.FullName -Force -Recurse: Removes the empty subdirectories.

    Important notes:

    • Make sure to run PowerShell as an administrator if you encounter any permission issues.
    • Backup your files before running the script to prevent accidental data loss.