COULD YOU SHow me a sample powershell script to backup a folder with subfolders using 7-zip?

Jerrold Weisdock 0 Reputation points
2026-10-04T18:38:02.0133333+00:00

COULD YOU SHow me a sample powershell script to backup a folder with subfolders using 7-zip?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Marcin Policht 109.7K Reputation points MVP Volunteer Moderator
    2026-10-04T19:48:11.6033333+00:00

    Yep - this one uses the 7-Zip command-line executable to recursively back up a folder and all subfolders into a timestamped .7z archive.

    # Source folder to back up
    $SourceFolder = "C:\Users\Username"
    
    # Backup destination
    $BackupFolder = "D:\Backups"
    
    # Path to 7-Zip
    $SevenZip = "C:\Program Files\7-Zip\7z.exe"
    
    # Create backup folder if it does not exist
    if (-not (Test-Path $BackupFolder)) {
        New-Item -Path $BackupFolder -ItemType Directory -Force | Out-Null
    }
    
    # Create timestamp
    $Timestamp = Get-Date -Format "yyyy-MM-dd-HH-mm-ss"
    
    # Archive filename
    $Archive = Join-Path $BackupFolder "UserProfile_$Timestamp.7z"
    
    # Verify 7-Zip exists
    if (-not (Test-Path $SevenZip)) {
        Write-Error "7-Zip was not found at $SevenZip"
        exit 1
    }
    
    # Verify source exists
    if (-not (Test-Path $SourceFolder)) {
        Write-Error "Source folder was not found: $SourceFolder"
        exit 1
    }
    
    # Create 7-Zip archive
    & $SevenZip a -t7z $Archive "$SourceFolder\*" -mx=5 -mmt=on
    
    # Check result
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Backup completed successfully:"
        Write-Host $Archive
    }
    else {
        Write-Error "7-Zip backup failed. Exit code: $LASTEXITCODE"
        exit $LASTEXITCODE
    }
    
    

    The a command adds files to the archive, -t7z creates a 7z archive, "$SourceFolder\*" includes the contents of the folder recursively, -mx=5 uses moderate compression, and -mmt=on enables multithreaded compression.

    For example, backing up C:\Users\John could produce:

    D:\Backups\UserProfile_2026-10-04-15-52-31.7z


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.