如何用Robocopy结合时间戳创建带日期时间的文件夹?
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:15for 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
SETreplaces spaces in the time with0(so9becomes09for consistent formatting). - The second
SETreplaces colons with hyphens to avoid invalid folder name characters. - The final
IFstatement 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 -Formatgives you full control over the timestamp structure (no spaces, consistent date/time formatting).$env:BUILD_SOURCESDIRECTORYis 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

