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

如何用Robocopy结合时间戳创建带日期时间的文件夹?

Fixing Robocopy Command to Create Timestamped Folders & Resolve Exit Code 1 Error

Let's break down what's going wrong and fix your Robocopy command step by step:

1. Understand the Exit Code 1 "Error"

First, a critical note: Robocopy uses bitmask exit codes, not the traditional 0=success/non-0=failure rule. Exit code 1 actually means at least one file was copied successfully—this is a normal, successful state! The issue is that CI/CD environments like Azure DevOps treat any non-0 exit code as a failure. We'll address this later.

2. Fix the Timestamp Variable Issues

Your current %date:/=-%_%time::=-% syntax works in CMD, but has two potential pitfalls:

  • The %time% variable can include leading spaces (e.g., 9:30:15 for morning times), which creates folder names with spaces and can cause path parsing errors in Robocopy.
  • If you're running this in a PowerShell context (common in Azure DevOps), %date% and %time% are CMD-style variables and won't be parsed correctly.

Solution for CMD:

Use a formatted timestamp without spaces by padding the time components, then handle Robocopy's exit codes properly:

SET "timestamp=%date:/=-%_%time: =0%"
SET "timestamp=%timestamp::=-%"
ROBOCOPY "%BUILD_SOURCESDIRECTORY%\sourcefolder\" "\\server\destination\%timestamp%" /V
:: Robocopy exit codes 0-7 represent successful states (bitmask logic)
IF %ERRORLEVEL% LEQ 7 EXIT 0
EXIT %ERRORLEVEL%
  • The first SET replaces spaces in the time with 0 (so 9 becomes 09 for consistent formatting).
  • The second SET replaces colons with hyphens to avoid invalid folder name characters.
  • The final IF statement tells the CI/CD pipeline that exit codes 0-7 are valid successes.

Solution for PowerShell:

Use PowerShell's native Get-Date cmdlet to generate a clean timestamp, and handle exit codes appropriately:

$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$destinationPath = "\\server\destination\$timestamp"
robocopy "$env:BUILD_SOURCESDIRECTORY\sourcefolder\" $destinationPath /V

# Robocopy exit codes 0-7 are successful; 8+ indicate actual errors
if ($LASTEXITCODE -le 7) {
    exit 0
} else {
    exit $LASTEXITCODE
}
  • Get-Date -Format gives you full control over the timestamp structure (no spaces, consistent date/time formatting).
  • $env:BUILD_SOURCESDIRECTORY is the correct way to access environment variables in PowerShell.

3. Verify Folder Creation

Robocopy will automatically create the destination folder if it doesn't exist—you don't need a separate mkdir command. Just ensure the user running the command has write permissions to \\server\destination\.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:57:42