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

如何改进GoPro视频合并PowerShell脚本并修复路径问题

修复后的GoPro视频合并脚本

以下是修复了路径问题并重构后的脚本,支持自动使用脚本所在目录或手动指定目标目录,彻底解决merge文件生成失败/为空的问题:

param(
    [string]$TargetPath = $PSScriptRoot
)

# 验证目标目录存在
if (-not (Test-Path -Path $TargetPath -PathType Container)) {
    Write-Error "目标目录不存在:$TargetPath"
    exit 1
}

# 获取目录下所有MP4文件
$oldvids = Get-ChildItem -Path $TargetPath -Filter *.mp4 -File
foreach ($oldvid in $oldvids) {
    $name = [System.IO.Path]::GetFileNameWithoutExtension($oldvid)
    $ext = [System.IO.Path]::GetExtension($oldvid)

    # 只处理GX01开头且未合并过的视频
    if ($name -notmatch '^GX01' -or $name -match '_merged$') {
        continue
    }

    $newVidPath = Join-Path -Path $oldvid.DirectoryName -ChildPath "$name`_merged$ext"
    # 检查是否已合并
    if (Test-Path -Path $newVidPath -PathType Leaf) {
        Write-Host "$name | 已合并"
        continue
    }

    # 查找连续的后续视频片段(GX02到GX09)
    $maxSegment = 1
    for ($num = 2; $num -le 9; $num++) {
        $segmentName = $name -replace 'GX01', "GX0$num"
        $segmentPath = Join-Path -Path $oldvid.DirectoryName -ChildPath "$segmentName$ext"
        if (Test-Path -Path $segmentPath -PathType Leaf) {
            $maxSegment = $num
        } else {
            # 中间断了就停止查找
            break
        }
    }

    # 只有单个片段则跳过
    if ($maxSegment -eq 1) {
        Write-Host "$name | 单段视频,无需合并"
        continue
    }

    # 生成merge文件路径(用绝对路径避免ffmpeg识别问题)
    $mergeFilePath = Join-Path -Path $oldvid.DirectoryName -ChildPath 'mergevideos.txt'
    # 清空或创建merge文件
    Set-Content -Path $mergeFilePath -Value $null -Force

    # 写入所有片段的绝对路径到merge文件
    for ($num = 1; $num -le $maxSegment; $num++) {
        $segmentName = $name -replace 'GX01', "GX0$num"
        $segmentFullPath = Join-Path -Path $oldvid.DirectoryName -ChildPath "$segmentName$ext"
        Add-Content -Path $mergeFilePath -Value "file '$segmentFullPath'"
    }

    Write-Host "$name | 正在合并 $maxSegment 段视频..."
    # 调用ffmpeg合并
    ffmpeg -f concat -safe 0 -i $mergeFilePath -c copy $newVidPath

    # 可选:合并完成后删除merge文件
    # Remove-Item -Path $mergeFilePath -Force
}

关键改进说明

  • 标准化路径处理:全程使用Join-Path拼接路径,彻底解决手动字符串拼接导致的分隔符错误,这是原脚本merge文件生成失败的核心原因
  • 灵活目录选择:
    • 默认使用脚本所在目录($PSScriptRoot),无需移动脚本即可处理当前目录视频
    • 可通过参数指定目标目录,例如:.\Merge-GoProVideos.ps1 -TargetPath "D:\GoPro\TravelVideos"
  • 严谨的片段查找逻辑:遇到不存在的片段时立即停止循环,避免无效遍历
  • 绝对路径写入merge文件:确保ffmpeg能精准识别视频文件,规避相对路径导致的文件找不到问题
  • 简化条件判断:用正则表达式替代StartsWith/EndsWith,代码更简洁高效
  • 前置错误检查:先验证目标目录有效性,提前终止并给出明确错误提示

使用方法

  1. 将脚本保存为Merge-GoProVideos.ps1
  2. 直接运行:自动处理脚本所在目录的GoPro视频
  3. 指定目录运行:在PowerShell中执行带参数的命令,指定要处理的视频目录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:25:23