如何在Windows 11会话启动时每月仅执行一次任务
实现会话启动触发的每月单次任务方案
方案一:原生任务计划「错过补执行」设置(推荐)
不需要额外脚本,直接用Windows任务计划的内置功能就能解决:
- 创建任务时,触发器选择「每月」,设置为你期望的基准时间(比如每月1日8:00)
- 进入触发器的「设置」面板,勾选**「如果错过计划的启动时间,立即启动任务」**
- 切换到任务的「设置」选项卡,勾选**「如果任务已经在运行,则不要启动新实例」**
原理:不管电脑在基准时间是否开机,只要当月第一次开机登录,系统会自动检测到「错过的任务」并立即执行;任务执行后,当月的触发器不会再次触发,确保每月仅执行一次。
方案二:标记文件法(简单易上手)
通过创建当月专属的标记文件,判断任务是否已执行:
- 创建一个登录触发的任务(触发器选「当用户登录时」)
- 任务操作选择「启动程序」,程序路径设为
powershell.exe,参数填你写好的脚本路径(比如-File "C:\Scripts\MonthlyTaskChecker.ps1") - 脚本内容示例:
$currentMonth = Get-Date -Format "yyyy-MM" $markerDir = "C:\TaskMarkers" $markerFile = Join-Path $markerDir "MonthlyTask_$currentMonth.txt" # 确保标记目录存在 if (-not (Test-Path $markerDir)) { New-Item -Path $markerDir -ItemType Directory -Force | Out-Null } # 检查当月是否已执行任务 if (-not (Test-Path $markerFile)) { # 替换成你的实际任务命令 Start-Process "C:\YourTask.exe" -Wait # 创建当月标记文件 New-Item -Path $markerFile -ItemType File -Force # 清理3个月前的旧标记文件,避免冗余 Get-ChildItem $markerDir | Where-Object { $_.Name -match '\d{4}-\d{2}' -and [datetime]($_.Name -replace 'MonthlyTask_|\.txt','') -lt (Get-Date).AddMonths(-3) } | Remove-Item -Force }
方案三:注册表记录法(隐蔽无文件)
把执行记录存在注册表,避免标记文件被误删:
- 同样创建登录触发的任务,执行PowerShell脚本
- 脚本内容示例:
$currentMonth = Get-Date -Format "yyyy-MM" $regPath = "HKCU:\Software\YourTaskConfigs" $regValue = "LastExecutedMonth" # 创建注册表项(如果不存在) if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force | Out-Null } $lastExecuted = Get-ItemProperty -Path $regPath -Name $regValue -ErrorAction SilentlyContinue | Select-Object -ExpandProperty $regValue -ErrorAction SilentlyContinue if ($lastExecuted -ne $currentMonth) { # 执行你的任务 & "C:\YourTaskScript.bat" # 更新注册表记录 Set-ItemProperty -Path $regPath -Name $regValue -Value $currentMonth -Force }
各方案对比
- 方案一:无额外脚本依赖,系统原生支持,最省心,优先推荐
- 方案二:逻辑直观,适合新手排查问题,缺点是标记文件可能被误删
- 方案三:无本地文件残留,隐蔽性强,适合对系统整洁度有要求的场景
内容的提问来源于stack exchange,提问作者M'sieur Toph'
相关产品推荐
相关产品推荐

