如何用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:
- First, calculate the date two months from today and format it to match
schtasks's expectedMM/dd/yyyyformat. - 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 /cprefix is necessary becausedelis a Command Prompt internal command—schtasksrequires a valid executable path, so we usecmd.exeto run the delete command. - If your system uses a different date format (e.g.,
dd/MM/yyyyin some regions), adjust theToStringformat string to match whatschtasksexpects 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.
- 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
- 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/fflag toschtasksto overwrite it (e.g.,schtasks /create /f /tn ...).
内容的提问来源于stack exchange,提问作者LonsomeHell

