求助: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-ChildItemto recursively scan all subfolders under your root share, then filters out any folders accessed within the last 365 days. - Local Archiving: Saves the
.7zarchive directly in the parent folder of the target subfolder (e.g.,C:\share\folder1.7zforC:\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
$7zipExevariable 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-WhatIfto theGet-ChildItemcommand 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.exebefore processing.
Customization Tips
- Adjust Threshold: Change
AddDays(-365)toAddMonths(-12)orAddYears(-1)for more readable time spans. - Compression Speed: Swap
-mx9with-mx5for 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" -Appendto the end ofWrite-Host,Write-Warning, andWrite-Errorlines.
内容的提问来源于stack exchange,提问作者jack
相关产品推荐
相关产品推荐

