Files
SceneMarshal/scripts/explorer-media-rename.ps1
T
ali 5b0a932bfc fix(menu): 取消被误报为失败的根因修复,并容忍输入法全角 q
- 根因:worker 用 pwsh -Command '& 脚本' 调用时,脚本内的 exit 只结束脚本体,
  宿主进程按「最后一条命令是否成功」决定自己的退出码,于是取消(2)被报成 1
  修复:命令末尾补 '; exit \0' 显式传递退出码
- media-archive 的分类与确认输入先做 NFKC 归一化:中文输入法打出的全角
  「q」不再被判为未知分类并反复重试
- 实测:全角q取消 → 退出码 2;check 成功路径仍为 0
2026-11-19 18:54:28 +08:00

300 lines
11 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#Requires -Version 7.0
<#
.SYNOPSIS
资源管理器右键菜单的入口,支持「多选排队、单窗口顺序处理」。
.DESCRIPTION
三种运行方式:
1) 入队(菜单用):-Enqueue -Action <动作> -Paths <路径>
把任务写进队列后立即退出,由 worker 统一处理。多次点击只会拉起一个窗口。
2) 队列 worker(内部使用):-Worker
串行消费队列;队列处理完即退出(不等新任务)。
同一时刻只允许一个 worker(靠 worker.lock 独占锁保证)。
3) 直接执行(调试/手动):-Action <动作> -Paths <路径>
不进队列,立即处理当前窗口里的这一项。
.PARAMETER Action
rename(默认)/ archive / extract-subs / check。
.PARAMETER DryRun
只打印将要执行的远端命令,不真正执行。
.PARAMETER Pause
执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。
.PARAMETER Paths
资源管理器传入的选中项。
#>
[CmdletBinding()]
param(
[ValidateSet('rename', 'archive', 'extract-subs', 'check')]
[string]$Action = 'rename',
[switch]$Pause,
[switch]$DryRun,
[switch]$Enqueue,
[switch]$Worker,
[Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @()
)
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { }
# ---------------------------------------------------------------- 公共定义
$QueueDir = Join-Path $env:LOCALAPPDATA 'SceneMarshal'
$QueueFile = Join-Path $QueueDir 'queue.jsonl'
$QueueLock = Join-Path $QueueDir 'queue.lock'
$WorkerLock = Join-Path $QueueDir 'worker.lock'
$SpawnLock = Join-Path $QueueDir 'spawn.lock'
$WorkerLog = Join-Path $QueueDir 'worker.log'
$PwshPath = (Get-Process -Id $PID).Path
$ActionPlan = @{
'archive' = @{ Runner = 'media-archive.ps1'; Extra = @() }
'extract-subs' = @{ Runner = 'media-rename.ps1'; Extra = @('extract-subs') }
'check' = @{ Runner = 'media-rename.ps1'; Extra = @('check') }
'rename' = @{ Runner = 'media-rename.ps1'; Extra = @() }
}
function Write-WorkerLog([string]$message) {
try {
$line = '{0} {1}' -f (Get-Date).ToString('yyyy-MM-dd HH:mm:ss'), $message
Add-Content -LiteralPath $WorkerLog -Value $line -Encoding utf8
}
catch { }
}
function Enter-FileLock([string]$path, [int]$timeoutMs = 3000) {
$deadline = (Get-Date).AddMilliseconds($timeoutMs)
while ((Get-Date) -lt $deadline) {
try { return [IO.File]::Open($path, 'OpenOrCreate', 'ReadWrite', 'None') }
catch { Start-Sleep -Milliseconds 50 }
}
return $null
}
function Add-QueueItem([string]$action, [string]$target) {
New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null
$lock = Enter-FileLock $QueueLock
if ($null -eq $lock) { throw '队列被占用,请稍后重试' }
try {
$item = [ordered]@{ action = $action; path = $target; ts = (Get-Date).ToString('o') }
Add-Content -LiteralPath $QueueFile -Value ($item | ConvertTo-Json -Compress) -Encoding utf8
}
finally { $lock.Close() }
}
function Take-QueueItem {
New-Item -ItemType Directory -Force -Path $QueueDir | Out-Null
$lock = Enter-FileLock $QueueLock
if ($null -eq $lock) { return $null }
try {
if (-not (Test-Path -LiteralPath $QueueFile)) { return $null }
$lines = @(Get-Content -LiteralPath $QueueFile -Encoding utf8 | Where-Object { $_.Trim() })
if ($lines.Count -eq 0) {
Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue
return $null
}
$first = $lines[0]
$rest = @($lines | Select-Object -Skip 1)
if ($rest.Count -eq 0) {
Remove-Item -LiteralPath $QueueFile -Force -ErrorAction SilentlyContinue
}
else {
Set-Content -LiteralPath $QueueFile -Value $rest -Encoding utf8
}
return ($first | ConvertFrom-Json)
}
finally { $lock.Close() }
}
function Test-WorkerAlive {
$lock = Enter-FileLock $WorkerLock 200
if ($null -eq $lock) { return $true }
$lock.Close()
return $false
}
function Start-Worker {
Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-File', $PSCommandPath, '-Worker') `
-WindowStyle Normal | Out-Null
# 等它真正拿到锁再返回,避免同一批多选时重复拉起 worker
for ($i = 0; $i -lt 30; $i++) {
Start-Sleep -Milliseconds 50
if (Test-WorkerAlive) { return }
}
}
function Resolve-Target([string[]]$rawPaths) {
$target = $rawPaths | Where-Object { $_ } | Select-Object -First 1
if (-not $target) { return $null }
if (Test-Path -LiteralPath $target -PathType Leaf) {
return (Split-Path -Parent $target)
}
return $target
}
function Invoke-Action([string]$itemAction, [string]$target) {
$plan = $ActionPlan[$itemAction]
if (-not $plan) {
Write-Host "❌ 未知动作: $itemAction" -ForegroundColor Red
return 1
}
$runnerPath = Join-Path $PSScriptRoot $plan.Runner
$tokens = @($target) + $plan.Extra
# 关键:用独立子进程「继承当前控制台」来跑,而不是在进程内 + 管道。
# 管道会让远端 ssh -t 的交互提示与本地输入回显错位(提示行会消失)。
$quotedTokens = ($tokens | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ','
$quotedRunner = "'" + ($runnerPath -replace "'", "''") + "'"
$extra = ''
if ($DryRun) { $extra = ' -DryRun' }
# 末尾必须显式 exit:脚本里的 exit 只结束脚本体,-Command 宿主会按
# 「最后一条命令是否成功」给退出码,取消(code 2)会被错报成 1。
$command = "& $quotedRunner -Tokens @($quotedTokens)$extra; exit " + '$LASTEXITCODE'
$proc = Start-Process -FilePath $PwshPath `
-ArgumentList @('-NoLogo', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-Command', ('"' + $command + '"')) `
-NoNewWindow -Wait -PassThru
if ($null -eq $proc) { return 1 }
return [int]$proc.ExitCode
}
# ---------------------------------------------------------------- worker 模式
function Invoke-Worker {
Write-WorkerLog 'worker 进程启动(抢锁中)'
$workerLock = Enter-FileLock $WorkerLock 200
if ($null -eq $workerLock) {
Write-WorkerLog '已有 worker 在运行,本次进程直接退出'
Write-Host '已有 worker 在运行,退出。' -ForegroundColor DarkGray
return 0
}
try { $Host.UI.RawUI.WindowTitle = 'SceneMarshal 队列' } catch { }
Write-WorkerLog ("worker 启动(stdin重定向={0} stdout重定向={1})" -f `
[Console]::IsInputRedirected, [Console]::IsOutputRedirected)
Write-Host '📋 SceneMarshal 队列已启动' -ForegroundColor Cyan
Write-Host ''
$done = 0
$failed = 0
$cancelled = 0
$summaryShown = $false
$closeDeadline = $null
while ($true) {
$item = Take-QueueItem
if ($null -ne $item) {
$summaryShown = $false
$closeDeadline = $null
$name = Split-Path -Leaf $item.path
Write-Host ('─── [{0}] {1}' -f $item.action, $name) -ForegroundColor Yellow
Write-WorkerLog ("开始处理 {0} :: {1}" -f $item.action, $item.path)
$started = Get-Date
try {
$code = Invoke-Action $item.action $item.path
}
catch {
Write-Host (" ❌ 异常: {0}" -f $_.Exception.Message) -ForegroundColor Red
$code = 1
}
$cost = [int]((Get-Date) - $started).TotalSeconds
if ($code -eq 0) {
$done++
Write-Host (" ✅ 完成,用时 {0}s" -f $cost) -ForegroundColor Green
Write-WorkerLog ("完成 {0}({1}s)" -f $item.path, $cost)
}
elseif ($code -eq 2) {
# 退出码 2 约定为「用户主动取消」,不算失败
$cancelled++
Write-Host (" ⏭ 已取消(未改动任何文件),用时 {0}s" -f $cost) -ForegroundColor DarkYellow
Write-WorkerLog ("已取消 {0}" -f $item.path)
}
else {
$failed++
Write-Host (" ⚠️ 失败(退出码 {0}),用时 {1}s" -f $code, $cost) -ForegroundColor Red
Write-WorkerLog ("失败 {0}(code={1}, {2}s)" -f $item.path, $code, $cost)
}
Write-Host ''
continue
}
# 队列已空:只显示一次汇总,然后等按键关闭窗口
if (-not $summaryShown) {
Write-Host ('📊 本次共处理 {0} 项:成功 {1},取消 {2},失败 {3}' -f `
($done + $cancelled + $failed), $done, $cancelled, $failed) -ForegroundColor Cyan
Write-Host ' 按任意键(Esc / Enter)关闭窗口;期间有新任务会接着处理(2 分钟无操作自动关闭)' -ForegroundColor DarkGray
Write-WorkerLog ("队列处理完毕:成功 {0},取消 {1},失败 {2}" -f $done, $cancelled, $failed)
$summaryShown = $true
$closeDeadline = (Get-Date).AddSeconds(120)
}
$pressed = $false
try {
if ($Host.UI.RawUI.KeyAvailable) {
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
$pressed = $true
}
}
catch { }
if ($pressed) { break }
if ($null -ne $closeDeadline -and (Get-Date) -ge $closeDeadline) { break }
Start-Sleep -Milliseconds 150
}
Write-WorkerLog 'worker 退出'
$workerLock.Close()
return 0
}
# ---------------------------------------------------------------- 主流程
if ($Worker) {
exit (Invoke-Worker)
}
$target = Resolve-Target $Paths
if ($Enqueue) {
if (-not $target) { exit 0 } # 没拿到路径就静默退出,不弹窗
Add-QueueItem $Action $target
if (-not (Test-WorkerAlive)) {
# 多选时 Explorer 会同时发起 N 个入队调用,这里必须串行化,
# 否则每个调用都会在 worker 抢到锁之前各拉起一个窗口。
$spawnLock = Enter-FileLock $SpawnLock 8000
try {
if ($null -ne $spawnLock -and -not (Test-WorkerAlive)) { Start-Worker }
}
finally {
if ($null -ne $spawnLock) { $spawnLock.Close() }
}
}
exit 0
}
# 直接执行模式
if (-not $target) {
Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red
if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null }
exit 1
}
Write-Host "📁 目标: $target" -ForegroundColor DarkGray
Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray
$exitCode = Invoke-Action $Action $target
if ($Pause) {
Write-Host ''
Read-Host '按 Enter 关闭窗口' | Out-Null
}
exit $exitCode