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

PowerShell遍历客户文件夹执行归档脚本遇路径错误求助

解决PowerShell遍历子文件夹处理.rpt文件时的路径缺失问题

问题背景

原本有一段能正常运行的PowerShell脚本,可对指定文件夹内的.rpt文件按LastWriteTime降序排序,保留最新文件并将其余文件移至归档目录:

Get-ChildItem "\\networkfolder\RawData\2_ActionData_Prep\CustomerA\" -Recurse -Filter "*.rpt" -File |               
    Sort-Object -Property LastWriteTime -Descending | 
    Select-Object -Skip 1 |                                                          
    Move-Item -Force -Destination "\\networkfolder\RawData\_Archive\Archive_DataRetrieved\"

当尝试修改脚本遍历多个客户文件夹时,第一次修改的脚本无任何反应也不报错;添加$folder参数后,出现错误:Get-ChildItem : Cannot find path '\networkfolder\CustomerA' because it does not exist.——明明$CustomerFolders变量里存的是完整路径,却缺失了\RawData\2_ActionData_Prep\部分。

错误原因

Get-ChildItem返回的是DirectoryInfo对象,直接将$folder传给Get-ChildItem时,PowerShell会隐式调用对象的Name属性而非FullName属性,导致传入的路径不完整,只包含文件夹名称而非完整路径。

修正后的脚本

只需将$folder改为$folder.FullName,明确传入完整路径即可解决问题:

$CustomerFolders = Get-ChildItem -Path "\\networkfolder\RawData\2_ActionData_Prep\" -Directory -Recurse

foreach ($folder in $CustomerFolders) {
    Get-ChildItem -Path $folder.FullName -Filter "*.rpt" -File | 
        Sort-Object -Property LastWriteTime -Descending | 
        Select-Object -Skip 1 |                                                          
        Move-Item -Force -Destination "\\networkfolder\RawData\_Archive\Archive_DataRetrieved\"
}

可选优化:避免归档文件重名

如果不同客户文件夹下存在同名.rpt文件,直接移到同一归档目录会导致文件覆盖。可以按原客户文件夹结构在归档目录中创建对应子目录,保留文件的层级关系:

$archiveRoot = "\\networkfolder\RawData\_Archive\Archive_DataRetrieved\"
$CustomerFolders = Get-ChildItem -Path "\\networkfolder\RawData\2_ActionData_Prep\" -Directory -Recurse

foreach ($folder in $CustomerFolders) {
    # 构建与原文件夹对应的归档子目录路径
    $archiveDir = Join-Path -Path $archiveRoot -ChildPath $folder.FullName.Substring($folder.Root.FullName.Length)
    # 若归档子目录不存在则创建
    if (-not (Test-Path -Path $archiveDir)) {
        New-Item -Path $archiveDir -ItemType Directory -Force | Out-Null
    }
    Get-ChildItem -Path $folder.FullName -Filter "*.rpt" -File | 
        Sort-Object -Property LastWriteTime -Descending | 
        Select-Object -Skip 1 |                                                          
        Move-Item -Force -Destination $archiveDir
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:10:33