You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:PowerShell实现子文件夹超期文件压缩并删除原文件

PowerShell Script to Archive Old Subfolders with 7-Zip

Got it, let's build a robust PowerShell script that checks all the boxes for your shared folder archiving needs. I’ve broken this down with explanations so you can adapt it easily to your server environment.

Here’s the complete script, followed by a breakdown of how it works:

# Define your root shared folder path
$rootPath = "C:\share"
# Set the access time threshold (365 days in the past)
$accessThreshold = (Get-Date).AddDays(-365)
# Path to 7z.exe (update this if 7-Zip isn't in your system PATH)
$7zipExe = "7z.exe"

# Get all subfolders that haven't been accessed in over a year
$oldSubfolders = Get-ChildItem -Path $rootPath -Directory -Recurse | 
                 Where-Object { $_.LastAccessTime -lt $accessThreshold }

foreach ($folder in $oldSubfolders) {
    # Create the archive path (stored in the same parent folder as the target)
    $archiveFilePath = Join-Path -Path $folder.Parent.FullName -ChildPath "$($folder.Name).7z"

    try {
        # Run 7-Zip to compress the folder and delete original files on success
        & $7zipExe a -t7z -mx9 -sdel "$archiveFilePath" "$($folder.FullName)\*"

        # Verify 7-Zip completed successfully
        if ($LASTEXITCODE -eq 0) {
            Write-Host "✅ Successfully archived and deleted: $($folder.FullName)"
        } else {
            Write-Warning "⚠️ Failed to archive $($folder.FullName). 7-Zip exit code: $LASTEXITCODE"
        }
    } catch {
        Write-Error "❌ Error processing $($folder.FullName): $_"
    }
}

Key Features & Explanations

  • Targeted Folder Filtering: Uses Get-ChildItem to recursively scan all subfolders under your root share, then filters out any folders accessed within the last 365 days.
  • Local Archiving: Saves the .7z archive directly in the parent folder of the target subfolder (e.g., C:\share\folder1.7z for C:\share\folder1).
  • 7-Zip Optimization:
    • -t7z: Enforces 7-Zip format for maximum compression
    • -mx9: Uses the highest compression level to save server space
    • -sdel: Only deletes original files/folders after the archive is created successfully (prevents data loss if compression fails)
  • Error Handling: Includes basic try/catch blocks and checks 7-Zip’s exit code to clearly report successes, warnings, and errors.

Critical Pre-Run Checks

  • 7-Zip Setup: Ensure 7-Zip is installed on your server. If it’s not in your system PATH, update the $7zipExe variable to the full path (e.g., "C:\Program Files\7-Zip\7z.exe").
  • Test First: Before running on production data, comment out the & $7zipExe ... line and run the script to see which folders will be targeted. You can also add -WhatIf to the Get-ChildItem command for a dry run.
  • Permissions: Make sure the account running the script has read, write, and delete permissions on all folders in the shared path.
  • Locked Folders: The script will fail if a folder is locked by an active process (e.g., an open file). If this is a common issue, you can add a check for open file handles using tools like handle.exe before processing.

Customization Tips

  • Adjust Threshold: Change AddDays(-365) to AddMonths(-12) or AddYears(-1) for more readable time spans.
  • Compression Speed: Swap -mx9 with -mx5 for faster compression (with slightly lower space savings).
  • Log Output: Redirect all messages to a log file by adding | Out-File -FilePath "C:\share_archive_log.txt" -Append to the end of Write-Host, Write-Warning, and Write-Error lines.

内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:42:48