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

PowerShell按规则移动指定.exe文件至目标子文件夹需求

解决方案:按规则移动指定.exe文件

针对你需要的按特定规则移动.exe文件的需求,我写了一个PowerShell脚本,直接在Windows环境就能运行,不用额外装工具,完全匹配你的要求:

# 替换为你的实际路径
$sourceFolder = "C:\Path\To\FolderA"
$targetRoot = "C:\Path\To\FolderB"

# 获取所有.exe文件并处理属性提取
Get-ChildItem -Path $sourceFolder -Filter "*.exe" -File | ForEach-Object {
    $fileName = $_.Name
    # 提取首两个连字符之间的custom-string(例:CICon-123-xxx.exe → CICon)
    $customString = ($fileName -split '-')[0]
    # 提取文件名中所有数字并转为整数,用于排序比较
    $number = [int]($fileName -replace '[^\d]', '')

    # 封装为自定义对象方便后续分组排序
    [PSCustomObject]@{
        File          = $_
        CustomString  = $customString
        Number        = $number
    }
} | Group-Object -Property CustomString | ForEach-Object {
    # 每组按数字降序排序,取前两个(数字最大的两个文件)
    $topTwoFiles = $_.Group | Sort-Object -Property Number -Descending | Select-Object -First 2

    foreach ($fileObj in $topTwoFiles) {
        # 构建目标路径:B\win\custom-string
        $targetPath = Join-Path -Path $targetRoot -ChildPath "win\$($fileObj.CustomString)"
        # 自动创建不存在的文件夹(含多级目录)
        if (-not (Test-Path -Path $targetPath)) {
            New-Item -Path $targetPath -ItemType Directory -Force | Out-Null
        }
        # 移动文件,-Force可覆盖同名文件(不需要可删除)
        Move-Item -Path $fileObj.File.FullName -Destination $targetPath -Force
        Write-Host "已移动文件:$($fileObj.File.Name) → $targetPath"
    }
}

脚本细节说明:

  • 路径配置:开头的$sourceFolder和$targetRoot需要你替换成实际的文件夹A、B路径。
  • custom-string提取:通过-split '-'分割文件名,取第一个片段就是首两个连字符之间的标识(比如CICon-456-demo.exe会提取出CICon)。
  • 数字排序逻辑:用正则替换掉非数字字符,转成整数后降序排列,确保每组只保留数字最大的两个文件。
  • 自动建文件夹:Test-Path检查路径是否存在,New-Item -Force可以一次性创建win和custom-string多级目录。

实际示例:

假设文件夹A里有这些文件:

  • CICon-100-setup.exe
  • CICon-200-run.exe
  • CICon-300-update.exe
  • TestApp-50-install.exe
  • TestApp-150-launch.exe

脚本运行后:

  • CICon组会保留数字最大的300和200,将CICon-300-update.exe、CICon-200-run.exe移动到B\win\CICon
  • TestApp组会保留150和50,将TestApp-150-launch.exe、TestApp-50-install.exe移动到B\win\TestApp

注意事项:

  1. 测试阶段可以把Move-Item换成Copy-Item,确认筛选和路径都正确后再改成移动操作。
  2. 确保你对文件夹A有读取权限,对文件夹B有写入权限。
  3. 如果需要提取特定位置的数字(比如只取第二个连字符前的数字),可以把数字提取逻辑改成$number = [int]($fileName -split '-')[1]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:25:37