我的问题是,.bat文件在第一次运行时不会复制现有文件fileA.mod。但是,当我再次运行.bat文件时,它将复制该文件。
有趣的是,当文件不包含if条件时,复制命令将首次运行良好。
@echo off
:: Run command: SO_script.bat DEV PRE 5617295
:: DEV, TEST or PROD
set TypeOfTask=%1
:: PRE, INTER or POST
set Process=%2
:: Identification number of investigated task
set NoOfTask=%3
if %TypeOfTask%==DEV (
set source=C:\ISPPT\TASK\%NoOfTask%
mkdir C:\AutomaticTests\DEV\%NoOfTask%
set destination=C:\AutomaticTests\DEV\%NoOfTask%
if %Process%==PRE (
copy %source%\fileA.mod %destination%
)
)
答案 0 :(得分:0)
此问题为duplicate,请勿将此答案标记为已接受。
我已经发布了它,以向您展示使用延迟扩展的示例并提供可能的替代方法。
此外,它还显示了您应该使用的其他最佳实践,例如缩进,正确注释以及用于设置和比较变量和字符串的推荐语法。
@Echo Off
Rem Run command: SO_script.bat DEV PRE 5617295
Rem DEV, TEST or PROD
Set "TypeOfTask=%~1"
Rem PRE, INTER or POST
Set "Process=%~2"
Rem Identification number of investigated task
Set "NoOfTask=%~3"
If "%TypeOfTask%"=="DEV" (
Set "source=C:\ISPPT\TASK\%NoOfTask%"
Set "destination=C:\AutomaticTests\DEV\%NoOfTask%"
SetLocal EnableDelayedExpansion
MD "!destination!" 2>Nul
If "%Process%"=="PRE" (
Copy /Y "!source!\fileA.mod" "!destination!">Nul
)
EndLocal
)
我还建议您向脚本添加某种形式的验证,以确保脚本以正确的顺序接收所有必需的输入参数,并且其值与可接受的数据匹配。
如果仅出于脚本中显示的目的使用变量名,那么您当然根本不能设置任何这些变量:
@Echo Off
Rem Run command: SO_script.bat DEV PRE 5617295
If "%~1"=="DEV" (
MD "C:\AutomaticTests\DEV\%~1" 2>Nul
If "%~2"=="PRE" (
Copy /Y "C:\ISPPT\TASK\%~1\fileA.mod" "C:\AutomaticTests\DEV\%~1">Nul
)
)
或者,您可以在括号块之前设置变量:
@Echo Off
Rem Run command: SO_script.bat DEV PRE 5617295
Rem DEV, TEST or PROD
Set "TypeOfTask=%~1"
Rem PRE, INTER or POST
Set "Process=%~2"
Rem Identification number of investigated task
Set "NoOfTask=%~3"
Rem Setting source and destination variables
Set "source=C:\ISPPT\TASK\%NoOfTask%"
Set "destination=C:\AutomaticTests\%TypeOfTask%\%NoOfTask%"
If "%TypeOfTask%"=="DEV" (
MD "%destination%" 2>Nul
If "%Process%"=="PRE" (
Copy /Y "%source%\fileA.mod" "%destination%">Nul
)
)