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

如何用Schtasks设置任务在当前日期加两个月后执行文件删除?

如何创建当前日期两个月后执行的文件删除计划任务?

Got it, let's tackle this problem. The core issue here is that schtasks doesn't support relative date values directly for the /sd parameter—you need to pass a specific date string. Here are two reliable ways to calculate the date two months from now and feed it into your task creation command:

方法1:使用PowerShell(推荐,更简洁)

PowerShell has built-in date manipulation tools that make this straightforward. You can calculate the target date and pass it directly to schtasks in one script block:

  1. First, calculate the date two months from today and format it to match schtasks's expected MM/dd/yyyy format.
  2. Then create the task with that date.

Here's the full example (replace C:\path\to\your\file.txt with the actual file you want to delete):

# Calculate two months from today, formatted as MM/dd/yyyy
$targetDate = (Get-Date).AddMonths(2).ToString('MM/dd/yyyy')

# Create the scheduled delete task
schtasks /create /tn "Delete Target File" /tr "cmd /c del ""C:\path\to\your\file.txt""" /sc once /sd $targetDate /st 00:00

注意点:

  • The cmd /c prefix is necessary because del is a Command Prompt internal command—schtasks requires a valid executable path, so we use cmd.exe to run the delete command.
  • If your system uses a different date format (e.g., dd/MM/yyyy in some regions), adjust the ToString format string to match what schtasks expects for your locale.

方法2:纯Command Prompt(Cmd)环境

If you need to stick strictly to Cmd (no PowerShell), you'll need a helper VBScript to calculate the future date—Cmd itself doesn't have native date arithmetic.

  1. Create a temporary VBScript file (e.g., GetFutureDate.vbs) with this code:
' Calculate date 2 months from today and output in MM/dd/yyyy format
dt = DateAdd("m", 2, Date)
formattedDate = Right("0" & Month(dt), 2) & "/" & Right("0" & Day(dt), 2) & "/" & Year(dt)
WScript.Echo formattedDate
  1. Run this script from Cmd to capture the target date, then use it in schtasks:
' Capture the future date from the VBScript
for /f "delims=" %%d in ('cscript //nologo GetFutureDate.vbs') do set targetDate=%%d

' Create the scheduled delete task
schtasks /create /tn "Delete Target File" /tr "cmd /c del ""C:\path\to\your\file.txt""" /sc once /sd %targetDate% /st 00:00

额外提示:

  • Always run your Cmd/PowerShell window as Administrator—creating scheduled tasks requires elevated permissions.
  • If a task with the same name (/tn) already exists, add the /f flag to schtasks to overwrite it (e.g., schtasks /create /f /tn ...).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:11:56