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

PowerShell脚本优化:按内容分类移动剩余文件至指定目录

解决PowerShell文件分类移动问题

原脚本仅能移动包含"CP2023"内容的.ca2文件,要实现匹配文件移至CP文件夹,剩余文件移至PDPA文件夹,可以通过循环遍历所有目标文件并判断内容的方式实现,修正后的脚本如下:

# 定义路径变量,方便后续修改
$sourceDir = "C:\Users\lawdv\Desktop\Pd-PC-Thermo\ARC\"
$cpDest = "C:\Users\lawdv\Desktop\Pd-PC-Thermo\CP"
$pdpaDest = "C:\Users\lawdv\Desktop\Pd-PC-Thermo\PDPA"

# 确保目标文件夹存在,不存在则创建
if (-not (Test-Path $cpDest)) { New-Item -ItemType Directory -Path $cpDest | Out-Null }
if (-not (Test-Path $pdpaDest)) { New-Item -ItemType Directory -Path $pdpaDest | Out-Null }

# 获取所有.ca2文件并遍历
Get-ChildItem -Path $sourceDir -Filter *.ca2 -Recurse | ForEach-Object {
    # 检查文件内容是否包含"CP2023",-Quiet参数返回布尔值提升效率
    if ($_ | Select-String -Pattern "CP2023" -Quiet) {
        # 匹配则移至CP文件夹
        Move-Item -Path $_.FullName -Destination $cpDest
    }
    else {
        # 不匹配则移至PDPA文件夹
        Move-Item -Path $_.FullName -Destination $pdpaDest
    }
}

关键说明:

  • 先通过Test-Path和New-Item确保目标文件夹存在,避免移动时因文件夹不存在报错
  • 使用ForEach-Object遍历每个文件,对单个文件做内容判断
  • Select-String -Quiet直接返回布尔值,比默认返回匹配结果更高效,适合条件判断
  • 用变量定义路径,后续修改路径时只需改动变量值,更易维护

内容的提问来源于stack exchange,提问作者David V Lawson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:12:12