I'm trying to make a batch script to check each file in a directory and wait if one of them is currently being used by a process in windows. This solution is based on this answer from stackoverflow . The objective is to execute the following script in Jenkins before deploying an application using MSDeploy to make sure no dll is being used in the application folder:
FOR /F "delims=" %%A in ('dir C:\Folder\%1\*.dll /b') do (
:TestFile
ren C:\Folder\%1\%%A C:\Folder\%1\%%A
IF errorlevel 0 GOTO Continue
ping 127.0.0.1 -n 5 > nul
GOTO TestFile
:Continue
)
However when running this script, either as a stand-alone or through a Jenkins Windows Command step, it shows the following error when executing the FOR loop:
Warning: ) was unexpected at this time.
What could be the reason behind this error?
Thanks!
Using goto
breaks the loop context of for
; that causes the error you described. To work around that, you could move the code from the body of for
into a subroutine at the end of the batch script and use call
to execute it for each loop iteration. An exit /B
is necessary after the for
loop to not fall into the subroutine unintentionally after the loop has finished iterating.
Another issue is the error check for the ren
command, because the condition if ErrorLevel 0
is true for an ErrorLevel
equal to and greater than 0
; so the logic needs to be changed to if not ErrorLevel 1
, which is true if ErrorLevel
is less than 1
.
Here is the fixed code (you will notice, that I put some quotes around paths, and that I used the ~
modifier for some parameters; this has been done to guarantee that no problems arise with paths containing spaces or some other special characters):
for /F "delims=" %%A in ('dir /B "C:\Folder\%~1\*.dll"') do (
rem the processed items of the original code are passed as arguments:
call :TestFile "%~1" "%%~A"
)
exit /B
:TestFile
rem the delivered arguments can be accessed by `%1` and `%2` here:
2> nul ren "C:\Folder\%~1\%~2" "%~2"
if not ErrorLevel 1 goto :EOF
> nul ping 127.0.0.1 -n 5
goto :TestFile
The redirection 2> nul
at the ren
command avoids any error messages to be displayed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.