feat(menu): 右键菜单改为「入队 + 单 worker」,多选只弹一个窗口

- 新增 scripts/scenemarshal-enqueue.vbs:经 wscript 隐藏调用,点击后只入队,
  不再闪控制台窗口
- explorer-media-rename.ps1 支持三种模式:-Enqueue 入队并确保 worker 在跑;
  -Worker 串行消费队列;都不带则为原来的直接执行(调试用)
- worker 用 worker.lock 独占,保证同一时刻只有一个窗口;队列空 20 秒后自动退出
- 队列在 %LOCALAPPDATA%\\SceneMarshal\\queue.jsonl,处理记录写 worker.log
- 修复子脚本输出混进函数返回值、导致 worker 把成功误判成失败的问题(Out-Host)
- 实测:快速连续入队 3 项 → 1 个 worker 顺序处理完;含空格/中文/方括号的
  路径原样传递;退出码判定正确
This commit is contained in:
ali
2026-11-19 18:07:56 +08:00
parent f2d1986ff1
commit 65fe02f705
3 changed files with 249 additions and 37 deletions
+218 -36
View File
@@ -1,26 +1,32 @@
#Requires -Version 7.0 #Requires -Version 7.0
<# <#
.SYNOPSIS .SYNOPSIS
资源管理器右键菜单的入口:把选中的文件夹(或视频文件所在目录)交给对应动作。 资源管理器右键菜单的入口,支持「多选排队、单窗口顺序处理」。
.DESCRIPTION .DESCRIPTION
由 install-explorer-menu.ps1 注册成一个级联子菜单(SceneMarshal): 三种运行方式:
1. 重命名(自动) auto
2. 归档… media-archive 1) 入队(菜单用):-Enqueue -Action <动作> -Paths <路径>
3. 补外挂字幕(转码片源) extract-subs 把任务写进队列后立即退出,由 worker 统一处理。多次点击只会拉起一个窗口。
4. 入库前体检(只读) check
2) 队列 worker(内部使用):-Worker
串行消费队列;队列空且空闲超过 $WorkerIdleSeconds 秒后自行退出。
同一时刻只允许一个 worker(靠 worker.lock 独占锁保证)。
3) 直接执行(调试/手动):-Action <动作> -Paths <路径>
不进队列,立即处理当前窗口里的这一项。
.PARAMETER Action .PARAMETER Action
rename(默认)/ archive / extract-subs / check。 rename(默认)/ archive / extract-subs / check。
.PARAMETER Pause
执行结束后停住窗口,便于查看输出(由右键菜单传入)。
.PARAMETER DryRun .PARAMETER DryRun
只打印将要执行的远端命令,不真正执行(调试 / 验证路径翻译用)。 只打印将要执行的远端命令,不真正执行。
.PARAMETER Pause
执行结束后停住窗口(直接执行模式用);worker 结束时也会停一下。
.PARAMETER Paths .PARAMETER Paths
资源管理器传入的选中项(通常一个)。 资源管理器传入的选中项。
#> #>
[CmdletBinding()] [CmdletBinding()]
param( param(
@@ -28,50 +34,226 @@ param(
[string]$Action = 'rename', [string]$Action = 'rename',
[switch]$Pause, [switch]$Pause,
[switch]$DryRun, [switch]$DryRun,
[switch]$Enqueue,
[switch]$Worker,
[Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @() [Parameter(ValueFromRemainingArguments = $true)][string[]]$Paths = @()
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { } try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { }
# 动作 → (执行脚本, 附带模式参数) # ---------------------------------------------------------------- 公共定义
$plan = switch ($Action) {
'archive' { @{ Runner = 'media-archive.ps1'; Extra = @() } } $QueueDir = Join-Path $env:LOCALAPPDATA 'SceneMarshal'
'extract-subs' { @{ Runner = 'media-rename.ps1'; Extra = @('extract-subs') } } $QueueFile = Join-Path $QueueDir 'queue.jsonl'
'check' { @{ Runner = 'media-rename.ps1'; Extra = @('check') } } $QueueLock = Join-Path $QueueDir 'queue.lock'
default { @{ Runner = 'media-rename.ps1'; Extra = @() } } $WorkerLock = Join-Path $QueueDir 'worker.lock'
$WorkerLog = Join-Path $QueueDir 'worker.log'
$WorkerIdleSeconds = 20
$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 = @() }
} }
$target = $Paths | Where-Object { $_ } | Select-Object -First 1 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
# 注意:必须 Out-Host 把子脚本的输出导到控制台,
# 否则它会混进本函数的返回值,调用方拿到的就不是退出码了。
if ($DryRun) { & $runnerPath -Tokens $tokens -DryRun | Out-Host }
else { & $runnerPath -Tokens $tokens | Out-Host }
$code = $LASTEXITCODE
if ($null -eq $code -or $code -is [array]) { return 0 }
return [int]$code
}
# ---------------------------------------------------------------- worker 模式
function Invoke-Worker {
$workerLock = Enter-FileLock $WorkerLock 200
if ($null -eq $workerLock) {
Write-Host '已有 worker 在运行,退出。' -ForegroundColor DarkGray
return 0
}
try { $Host.UI.RawUI.WindowTitle = 'SceneMarshal 队列' } catch { }
Write-WorkerLog 'worker 启动'
Write-Host '📋 SceneMarshal 队列已启动(空闲 20 秒后自动关闭)' -ForegroundColor Cyan
Write-Host ''
$done = 0
$failed = 0
$idle = 0
$summarized = $false
while ($true) {
$item = Take-QueueItem
if ($null -eq $item) {
# 队列刚空时就报一次汇总,用户在窗口自动关闭前也能看到
if (($done + $failed) -gt 0 -and -not $summarized) {
Write-Host ('📊 已处理 {0} 项:成功 {1},失败 {2};{3} 秒内无新任务将自动关闭' -f `
($done + $failed), $done, $failed, $WorkerIdleSeconds) -ForegroundColor Cyan
$summarized = $true
}
if ($idle -ge $WorkerIdleSeconds) { break }
$idle += 2
Start-Sleep -Seconds 2
continue
}
$idle = 0
$summarized = $false
$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)
}
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 ''
}
Write-Host ('📊 本次共处理 {0} 项:成功 {1},失败 {2}' -f ($done + $failed), $done, $failed) -ForegroundColor Cyan
Write-Host (' 队列已空,{0} 秒内无新任务将自动关闭(详细记录见 worker.log)' -f $WorkerIdleSeconds) -ForegroundColor DarkGray
Write-WorkerLog ("worker 退出:成功 {0},失败 {1}" -f $done, $failed)
$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)) { Start-Worker }
exit 0
}
# 直接执行模式
if (-not $target) { if (-not $target) {
Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red Write-Host '❌ 没有收到要处理的路径' -ForegroundColor Red
if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null } if ($Pause) { Write-Host ''; Read-Host '按 Enter 关闭' | Out-Null }
exit 1 exit 1
} }
if (Test-Path -LiteralPath $target -PathType Leaf) {
$target = Split-Path -Parent $target
}
Write-Host "📁 目标: $target" -ForegroundColor DarkGray Write-Host "📁 目标: $target" -ForegroundColor DarkGray
Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray Write-Host ("▶ 动作: {0}" -f $Action) -ForegroundColor DarkGray
$runnerPath = Join-Path $PSScriptRoot $plan.Runner $exitCode = Invoke-Action $Action $target
$tokens = @($target) + $plan.Extra
if ($DryRun) {
& $runnerPath -Tokens $tokens -DryRun
}
else {
& $runnerPath -Tokens $tokens
}
$code = $LASTEXITCODE
if ($null -eq $code) { $code = 0 }
if ($Pause) { if ($Pause) {
Write-Host '' Write-Host ''
Read-Host '按 Enter 关闭窗口' | Out-Null Read-Host '按 Enter 关闭窗口' | Out-Null
} }
exit $code exit $exitCode
+8 -1
View File
@@ -37,6 +37,9 @@ $ErrorActionPreference = 'Stop'
$runner = Join-Path $PSScriptRoot 'explorer-media-rename.ps1' $runner = Join-Path $PSScriptRoot 'explorer-media-rename.ps1'
if (-not (Test-Path -LiteralPath $runner)) { throw "找不到 $runner" } if (-not (Test-Path -LiteralPath $runner)) { throw "找不到 $runner" }
$enqueueVbs = Join-Path $PSScriptRoot 'scenemarshal-enqueue.vbs'
if (-not (Test-Path -LiteralPath $enqueueVbs)) { throw "找不到 $enqueueVbs" }
$alias = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps\pwsh.exe' $alias = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps\pwsh.exe'
if (Test-Path -LiteralPath $alias) { if (Test-Path -LiteralPath $alias) {
# 应用执行别名,跨 PowerShell 版本升级保持稳定 # 应用执行别名,跨 PowerShell 版本升级保持稳定
@@ -77,7 +80,11 @@ $locations = @(
) )
function New-MenuCommand([string]$Action, [string]$Token) { function New-MenuCommand([string]$Action, [string]$Token) {
'"' + $pwsh + '" -NoLogo -NoProfile -File "' + $runner + '" -Action ' + $Action + ' -Pause "' + $Token + '"' # 经 wscript 调 VBS:无控制台窗口,只把任务写进队列,
# 由唯一的 worker 窗口按顺序处理(多选时不会弹多个终端)
$vbs = Join-Path $PSScriptRoot 'scenemarshal-enqueue.vbs'
$wscript = Join-Path $env:SystemRoot 'System32\wscript.exe'
'"' + $wscript + '" //nologo "' + $vbs + '" ' + $Action + ' "' + $pwsh + '" "' + $Token + '"'
} }
function Get-RegPath([string]$relative) { function Get-RegPath([string]$relative) {
+23
View File
@@ -0,0 +1,23 @@
' SceneMarshal 右键菜单的隐藏入口:把任务塞进队列后立即退出,不闪窗口。
' 参数:<动作> <pwsh 路径> <目标路径>
Option Explicit
Dim sh, fso, args, action, pwsh, target, scriptDir, script, cmd
If WScript.Arguments.Count < 3 Then WScript.Quit 1
action = WScript.Arguments(0)
pwsh = WScript.Arguments(1)
target = WScript.Arguments(2)
Set fso = CreateObject("Scripting.FileSystemObject")
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
script = scriptDir & "\explorer-media-rename.ps1"
cmd = """" & pwsh & """" & _
" -NoLogo -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass" & _
" -File """ & script & """" & _
" -Enqueue -Action " & action & " -Paths """ & target & """"
Set sh = CreateObject("WScript.Shell")
sh.Run cmd, 0, False