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

PowerShell脚本优化求助:仅归档7天前文件并压缩归档文件夹

修正PowerShell归档脚本:迁移旧文件并压缩归档文件夹

看起来你遇到的核心问题是原脚本错误地保留了源文件的完整目录结构,而且压缩逻辑没有针对归档后的文件夹。下面是修改后的完整脚本,直接实现「将NewFolder中超过7天的文件移动到Archive_folder,然后压缩该归档文件夹」的需求:

# 配置参数
$Days = 7
$SourcePath = "C:\Users\529817\New folder"
$TargetPath = "C:\Users\529817\New folder\Archive_folder"
$LogPath = "C:\Users\529817\Temp"
$Date = Get-Date -Format "yyyy-MM-dd_HH-mm"
$LogFile = "$LogPath\ArchiveLog-$Date.txt"
$TargetZipFile = "$TargetPath\$Date.zip"

# 确保归档目录和日志目录存在
if (-not (Test-Path $TargetPath)) {
    New-Item -Path $TargetPath -ItemType Directory | Out-Null
}
if (-not (Test-Path $LogPath)) {
    New-Item -Path $LogPath -ItemType Directory | Out-Null
}

$Activity = "Moving files older than $Days days from $SourcePath to $TargetPath"
Write-Verbose $Activity

# 获取SourcePath下的一级文件(不递归子目录),筛选7天前的
$OldFiles = Get-ChildItem -Path $SourcePath -File | 
            Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-$Days)}

if ($OldFiles.Count -eq 0) {
    "No files older than $Days days found to archive." | Add-Content $LogFile
    Write-Host "No files to archive."
    exit
}

$Total = $OldFiles.Count
$Current = 0

# 移动文件到归档目录(直接平级移动,不保留子目录)
$OldFiles | ForEach-Object {
    $Current++
    $FileName = $_.FullName
    Write-Progress -Activity $Activity -Status $FileName -PercentComplete ($Current / $Total * 100)

    try {
        Move-Item -Path $FileName -Destination $TargetPath -Force -ErrorAction Stop
        "Successfully moved $FileName to $TargetPath" | Add-Content $LogFile
    }
    catch {
        $Err = $_.Exception.Message
        Write-Error $Err
        "Error moving $FileName`: $Err" | Add-Content $LogFile
    }
}

# 压缩归档文件夹到指定ZIP文件
try {
    Compress-Archive -Path "$TargetPath\*" -DestinationPath $TargetZipFile -Force -ErrorAction Stop
    "Successfully compressed $TargetPath to $TargetZipFile" | Add-Content $LogFile
    Write-Host "Archive compression completed."
}
catch {
    $Err = $_.Exception.Message
    Write-Error $Err
    "Error compressing archive: $Err" | Add-Content $LogFile
}

关键修改说明:

  • 移除递归获取文件:用-File参数只获取源目录下的一级文件,避免递归子目录,这样就不会在归档目录里重建复杂路径
  • 直接移动文件:不再拆分路径,直接把文件移动到$TargetPath(Archive_folder),实现平级归档
  • 修复日志路径:把C:Users修正为C:\Users,避免路径错误
  • 确保目录存在:添加了Test-Path检查,自动创建归档目录和日志目录(如果不存在)
  • 压缩逻辑修正:压缩的是归档目录下的所有内容($TargetPath\*),而不是整个源目录,并且用-Force覆盖已存在的ZIP文件
  • 空状态处理:如果没有符合条件的旧文件,会记录日志并提前退出
  • 简化冗余变量:移除了未使用的$ArchiveYear/$ArchiveMonth/$ArchiveDay等变量,让代码更简洁

如果需要递归处理源目录下的所有子文件夹中的旧文件,但又不想在归档目录里保留子目录结构(即所有旧文件都平级放在Archive_folder里),只需要把Get-ChildItem的参数改成-File -Recurse即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:27:55