@echo off
setlocal EnableExtensions
chcp 65001 >nul 2>nul
title Mattermost Delayed Autostart Tool v1.1
set "MM_FIX_BAT=%~f0"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($env:MM_FIX_BAT)); $m=[char]10+'::===EMBEDDED_PS1_BEGIN==='; $i=$s.IndexOf($m); if($i -lt 0){'FATAL: embedded script not found'; exit 1}; $p=$s.Substring($i+$m.Length).TrimStart([char]13,[char]10); $t=Join-Path $env:TEMP 'mm_desktop_delayed_autostart.ps1'; [IO.File]::WriteAllText($t,$p,(New-Object Text.UTF8Encoding($true))); & $t %*"
exit /b %ERRORLEVEL%
::===EMBEDDED_PS1_BEGIN===
# =============================================================
# Mattermost 桌面端延迟自启一键工具 v1.1(内嵌脚本,勿单独分发)
# 功能:
# 1) 检测官方 / 二开客户端(二开含首载失败自动重试,无需本工具)
# 2) 关闭 MM 自带「登录时启动应用」(config.json + 注册表 Run + 启动目录快捷方式三形态)
# 3) 建立任务计划:登录时延迟 N 分钟(默认 1)启动 Mattermost
# 参数:
# /undo 回滚:删除计划任务(恢复自启请到 MM 设置里重开)
# /delay:NN 延迟分钟数(默认 1)
# /clean 仅清缓存重载:结束 MM -> 删 %APPDATA%\Mattermost 下缓存目录 -> 重启 MM
# (不动 config.json 与 Local Storage,登录状态/服务器列表保留)
# /q 静默模式(不暂停,供自动化测试)
# 设计:全部操作限当前用户级(HKCU / %APPDATA% / 当前用户任务),无需管理员权限
# =============================================================
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch { }
# ---------- 参数解析 ----------
$Undo = $false
$NoPause = $false
$Clean = $false
$DelayMin = 1
foreach ($a in $args) {
if ($a -match '^(?i)/undo$') { $Undo = $true; continue }
if ($a -match '^(?i)/q$') { $NoPause = $true; continue }
if ($a -match '^(?i)/clean$') { $Clean = $true; continue }
if ($a -match '^(?i)/delay:(\d+)$') { $DelayMin = [Math]::Max(1, [int]$Matches[1]); continue }
}
# ---------- 日志 ----------
$Lines = New-Object System.Collections.Generic.List[string]
function Say($s) { Write-Host $s; $Lines.Add($s) }
$LogPath = $null
if ($env:MM_FIX_BAT) {
try {
$d = Split-Path $env:MM_FIX_BAT -Parent
$LogPath = Join-Path $d 'mm_desktop_delayed_autostart.log'
$null = [IO.File]::AppendAllText($LogPath, '', [Text.Encoding]::UTF8)
} catch { $LogPath = $null }
}
if (-not $LogPath) { $LogPath = Join-Path $env:TEMP 'mm_desktop_delayed_autostart.log' }
function Finish([int]$code) {
Say ''
Say ('日志已保存: ' + $LogPath)
try {
$hdr = '---- ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + ' ----'
[IO.File]::AppendAllText($LogPath, ($hdr + [Environment]::NewLine + ($Lines -join [Environment]::NewLine) + [Environment]::NewLine + [Environment]::NewLine), [Text.Encoding]::UTF8)
} catch { Say ('[警告] 日志写入失败: ' + $_.Exception.Message) }
if (-not $NoPause) { Write-Host ''; Write-Host '按任意键退出...'; try { [Console]::ReadKey($true) | Out-Null } catch { } }
exit $code
}
# ---------- 常量 ----------
$Version = '1.1'
$TaskName = 'MattermostDelayedStart'
$ForkMarker = '__MM_RETRY_PATCH_V1__'
$RunPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
# 原生命令包装:局部降级错误级别,避免 PS5.1 下 stderr 在 EAP=Stop 时变终止错误
function Run-Native([string[]]$cmd) {
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
$out = & $cmd[0] $cmd[1..($cmd.Length - 1)] 2>&1 | Out-String
$rc = $LASTEXITCODE
$ErrorActionPreference = $eap
return , @($rc, $out)
}
# ---------- 工具函数 ----------
function Find-MmExe {
# 1) 注册表 Run 键值数据中含 mattermost 的路径
if (Test-Path $RunPath) {
$props = Get-ItemProperty -LiteralPath $RunPath
foreach ($n in $props.PSObject.Properties.Name) {
if ($n -match '^PS(Path|ParentPath|ChildName|Drive|Provider)$') { continue }
$v = '' + $props.$n
if ($v -match 'mattermost') {
$cand = $null
if ($v -match '^"\s*([^"]+\.exe)') { $cand = $Matches[1] }
elseif ($v -match '^\s*([^\s"]+\.exe)') { $cand = $Matches[1] }
if ($cand -and (Test-Path -LiteralPath $cand)) { return $cand }
}
}
}
# 2) 常见安装路径(per-user squirrel 安装 / per-machine MSI 安装)
$cands = @(
(Join-Path $env:LOCALAPPDATA 'Programs\mattermost-desktop\Mattermost.exe'),
(Join-Path $env:ProgramFiles 'Mattermost\Mattermost.exe'),
(Join-Path ${env:ProgramFiles(x86)} 'Mattermost\Mattermost.exe')
)
foreach ($c in $cands) { if ($c -and (Test-Path -LiteralPath $c)) { return $c } }
return $null
}
function Test-AsarMarker($asar) {
# 流式搜索标记串,避免整文件入内存
$mb = [Text.Encoding]::ASCII.GetBytes($ForkMarker)
$fs = [IO.File]::OpenRead($asar)
try {
$chunk = 1048576
$overlap = $mb.Length - 1
$prev = ''
$buf = New-Object byte[] $chunk
while ($true) {
$read = $fs.Read($buf, 0, $chunk)
if ($read -le 0) { break }
$str = $prev + [Text.Encoding]::ASCII.GetString($buf, 0, $read)
if ($str.IndexOf($ForkMarker) -ge 0) { return $true }
if ($str.Length -gt $overlap) { $prev = $str.Substring($str.Length - $overlap) } else { $prev = $str }
if ($read -lt $chunk) { break }
}
} finally { $fs.Close() }
return $false
}
function Test-Forked($exe) {
$dir = Split-Path $exe -Parent
if (Test-Path -LiteralPath (Join-Path $dir 'RETRY_PATCHED.marker')) { return $true }
$asar = Join-Path $dir 'resources\app.asar'
if (Test-Path -LiteralPath $asar) {
try { if (Test-AsarMarker $asar) { return $true } } catch { Say ('[警告] asar 扫描失败: ' + $_.Exception.Message) }
}
return $false
}
function Disable-Autostart {
# 形态 1:config.json 的 autostart(核心,防 MM 启动时回写注册表)
$cfg = Join-Path $env:APPDATA 'Mattermost\config.json'
if (Test-Path -LiteralPath $cfg) {
$json = Get-Content -LiteralPath $cfg -Raw -Encoding UTF8 | ConvertFrom-Json
$cur = $json.autostart
Copy-Item -LiteralPath $cfg -Destination ($cfg + '.bak_' + (Get-Date -Format 'yyyyMMdd_HHmmss')) -Force
if ($json.PSObject.Properties.Name -contains 'autostart') { $json.autostart = $false }
else { $json | Add-Member -NotePropertyName 'autostart' -NotePropertyValue $false }
# 必须无 BOM 的 UTF-8:PS 5.1 Set-Content -Encoding UTF8 带 BOM,MM 的 JSON.parse 不认 BOM,
# 会判配置损坏→回退默认值(autostart=true)并回写,防回写即失效(VM112 实证)
[IO.File]::WriteAllText($cfg, ($json | ConvertTo-Json -Depth 20), (New-Object Text.UTF8Encoding($false)))
Say (' [ok] config.json: autostart ' + $cur + ' -> false(原文件已备份 .bak_*)')
} else {
Say ' [跳过] config.json 不存在(MM 尚未首次启动)'
}
# 形态 2:注册表 Run 键
if (Test-Path $RunPath) {
$props = Get-ItemProperty -LiteralPath $RunPath
foreach ($n in @($props.PSObject.Properties.Name)) {
if ($n -match '^PS(Path|ParentPath|ChildName|Drive|Provider)$') { continue }
$v = '' + $props.$n
if ($v -match 'mattermost') {
Remove-ItemProperty -LiteralPath $RunPath -Name $n
Say (' [ok] 注册表 Run: 已删除 ' + $n)
}
}
}
# 形态 3:启动目录快捷方式
$startup = [Environment]::GetFolderPath('Startup')
Get-ChildItem -LiteralPath $startup -Filter '*.lnk' -ErrorAction SilentlyContinue | ForEach-Object {
$hit = ($_.Name -match 'mattermost')
if (-not $hit) {
try {
$sh = New-Object -ComObject WScript.Shell
$sc = $sh.CreateShortcut($_.FullName)
$hit = ($sc.TargetPath -match 'mattermost')
} catch { }
}
if ($hit) {
Remove-Item -LiteralPath $_.FullName -Force
Say (' [ok] 启动目录: 已删除 ' + $_.Name)
}
}
}
function New-DelayedTask($exe) {
# schtasks /Create /TR 对含空格路径会在首个空格处拆成 Command+Arguments(VM112 实证 0x80070002,
# 单双引号/转义均无效);改用 XML 注册法(schtasks /Create /XML),Command 原样保留。
# XML 必须 UTF-16 编码(可带可不带声明,UTF-8 被拒;VM112 实证)。
$xe = $exe.Replace('&','&').Replace('<','<').Replace('>','>')
$delay = ('PT{0}M' -f [int]$DelayMin)
$body = @'
true__DELAY__
InteractiveToken
LeastPrivilege
IgnoreNew
false
false
true
false
false
true
true
false
7
__EXE__
'@
$body = $body.Replace('__DELAY__', $delay).Replace('__EXE__', $xe)
$xf = Join-Path $env:TEMP 'mm_delayed_autostart_task.xml'
[IO.File]::WriteAllText($xf, ('' + [Environment]::NewLine + $body), [Text.Encoding]::Unicode)
$r = Run-Native @('schtasks', '/Create', '/TN', $TaskName, '/XML', $xf, '/F')
Remove-Item -LiteralPath $xf -Force -ErrorAction SilentlyContinue
if ($r[0] -ne 0) {
Say (' [失败] 创建计划任务失败 rc=' + $r[0] + ': ' + $r[1].Trim())
Finish 3
}
# 断言:回读 XML 确认 Command/Delay 均正确(防静默退化)
$q = Run-Native @('schtasks', '/Query', '/TN', $TaskName, '/XML')
$okCmd = ($q[1] -match '([^<]+)') -and ($Matches[1] -eq $exe)
$okDelay = ($q[1] -match '([^<]+)') -and ($Matches[1] -eq $delay)
if (-not ($okCmd -and $okDelay)) {
Say ' [失败] 任务自检不通过(Command 或 Delay 与预期不符),请反馈 IT'
Finish 3
}
Say (' [ok] 计划任务 ' + $TaskName + ' 已创建(登录时 + 延迟 ' + $DelayMin + ' 分钟)')
}
function Stop-MmProcesses {
# 先温和 CloseMainWindow,等 8 秒;仍在则强杀(保证缓存文件释放)
$procs = Get-Process -Name 'Mattermost' -ErrorAction SilentlyContinue
if (-not $procs) { Say ' Mattermost 未在运行'; return }
foreach ($p in $procs) { try { $null = $p.CloseMainWindow() } catch { } }
$deadline = (Get-Date).AddSeconds(8)
while ((Get-Date) -lt $deadline -and (Get-Process -Name 'Mattermost' -ErrorAction SilentlyContinue)) {
Start-Sleep -Milliseconds 500
}
if (Get-Process -Name 'Mattermost' -ErrorAction SilentlyContinue) {
Say ' 窗口未自行关闭,执行强制结束...'
Stop-Process -Name 'Mattermost' -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
}
if (Get-Process -Name 'Mattermost' -ErrorAction SilentlyContinue) {
Say ' [失败] Mattermost 进程无法结束,请手动退出后重试'
Finish 4
}
Say ' [ok] Mattermost 已全部退出'
}
function Invoke-CleanCache($exe) {
# 只删缓存类目录;保留 config.json(自启设置)与 Local Storage(登录会话/服务器列表)
$root = Join-Path $env:APPDATA 'Mattermost'
if (-not (Test-Path -LiteralPath $root)) {
Say ' [跳过] ' + $root + ' 不存在(MM 尚未首次启动,无缓存可清)'
} else {
$dirs = @('Cache', 'Code Cache', 'GPUCache', 'DawnCache', 'blob_storage')
$freed = 0
foreach ($d in $dirs) {
$p = Join-Path $root $d
if (Test-Path -LiteralPath $p) {
$sz = (Get-ChildItem -LiteralPath $p -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum
if (-not $sz) { $sz = 0 }
Remove-Item -LiteralPath $p -Recurse -Force -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath $p) {
Say (' [警告] ' + $d + ' 删除失败(可能仍被占用)')
} else {
$freed += $sz
Say (' [ok] 已清除 ' + $d + '(' + [Math]::Round($sz / 1MB, 1) + ' MB)')
}
}
}
Say (' 共释放约 ' + [Math]::Round($freed / 1MB, 1) + ' MB')
}
Say ' 重新启动 Mattermost...'
Start-Process -FilePath $exe
Say ' [ok] 已启动,首次加载会重建缓存,稍慢属正常'
}
function Show-Verify {
Say ''
Say '== 自检回执 =='
$cfg = Join-Path $env:APPDATA 'Mattermost\config.json'
if (Test-Path -LiteralPath $cfg) {
$j = Get-Content -LiteralPath $cfg -Raw -Encoding UTF8 | ConvertFrom-Json
Say (' config.json autostart = ' + $j.autostart)
}
$left = 0
if (Test-Path $RunPath) {
$props = Get-ItemProperty -LiteralPath $RunPath
foreach ($n in $props.PSObject.Properties.Name) {
if ($n -match '^PS(Path|ParentPath|ChildName|Drive|Provider)$') { continue }
if (('' + $props.$n) -match 'mattermost') { $left++ }
}
}
Say (' 注册表 Run 残留项 = ' + $left)
$r = Run-Native @('schtasks', '/Query', '/TN', $TaskName, '/XML')
if ($r[0] -eq 0) {
$xml = $r[1]
$dl = ''; $cm = ''
if ($xml -match '([^<]+)') { $dl = $Matches[1] }
if ($xml -match '([^<]+)') { $cm = $Matches[1] }
Say (' 计划任务 Delay = ' + $dl + ' / Command = ' + $cm)
} else {
Say ' 计划任务 = 不存在'
}
}
# ---------- 主流程 ----------
Say '==================================================='
Say (' Mattermost 桌面端延迟自启一键工具 v' + $Version)
Say ' 关 MM 自带自启 + 改为登录后延迟 N 分钟启动'
Say ' 附加:/clean 清缓存重载 | /undo 回滚'
Say '==================================================='
if ($Undo) {
Say ''
Say '== 回滚模式 =='
$r = Run-Native @('schtasks', '/Query', '/TN', $TaskName)
if ($r[0] -eq 0) {
$null = Run-Native @('schtasks', '/Delete', '/TN', $TaskName, '/F')
Say (' [ok] 已删除计划任务 ' + $TaskName)
} else {
Say ' 计划任务不存在,无需回滚'
}
Say ' 如需恢复 MM 自带自启:请在 Mattermost 设置里重新打开「登录时启动应用」。'
Finish 0
}
if ($Clean) {
Say ''
Say '== 清缓存重载模式(/clean) =='
$exe = Find-MmExe
if (-not $exe) {
Say '[错误] 未检测到 Mattermost 桌面端安装,退出。'
Finish 2
}
Stop-MmProcesses
Invoke-CleanCache $exe
Say ''
Say '完成。若问题仍在,可连用 2~3 次;仍无效请联系 IT。'
Finish 0
}
$exe = Find-MmExe
if (-not $exe) {
Say '[错误] 未检测到 Mattermost 桌面端安装(注册表 Run 与常见路径均无),退出。'
Finish 2
}
Say ('检测到安装路径: ' + $exe)
if (Test-Forked $exe) {
Say '检测到二开客户端(内嵌首载失败自动重试补丁),无需本工具,正常退出。'
Finish 0
}
# 进程检查:运行中的 MM 会在退出时把内存配置写回,覆盖我们的修改
while (Get-Process -Name 'Mattermost' -ErrorAction SilentlyContinue) {
Say ''
Say '检测到 Mattermost 正在运行。请先退出(托盘图标右键 -> Quit),然后按任意键继续。'
if ($NoPause) { Say '[警告] /q 模式:不等待,继续执行(运行实例退出时可能回写配置)。'; break }
try { [Console]::ReadKey($true) | Out-Null } catch { break }
}
Say ''
Say '== 第 1 步:关闭 MM 自带自启(三形态清理) =='
Disable-Autostart
Say ''
Say ('== 第 2 步:建立延迟自启(延迟 ' + $DelayMin + ' 分钟) ==')
New-DelayedTask $exe
Show-Verify
Say ''
Say '全部完成。下次登录系统后,Mattermost 将延迟 ' + $DelayMin + ' 分钟自动启动(网络先就绪、MM 后起)。'
Say '回滚方法:双击本工具加参数 /undo 。'
Finish 0