How to sort the arguments dropped to a batch file?

你。 提交于 2019-12-24 23:56:42

问题


I am writing a batch file that finds and executes all update.bat file inside all the directories dropped onto it.

The problem here is that I expect the arguments (i.e directories' path) comes in ordered by name but it turns out they are sorted by the modified date.

Is this the default behavior of Windows (Windows 7)? Any suggestion to solve this?


Here is my batch script:

@echo off
Setlocal EnableDelayedExpansion

if [%1]==[] goto :no_update_dropped

set LOG_FILE=update_log.txt

echo You are about to run these updates:
for %%G IN (%*) do (
  if exist %%~sG\NUL echo %%G
)

pause

for %%G IN (%*) do (
  if exist %%G\NUL (
        if exist %%G\update.bat (
            call %%G\update.bat %LOG_FILE%
        ) else (
            echo No update.bat found in %%G.
            goto :no_batch_found
        )
    )
)
goto :success

:no_update_dropped
echo NO UPDATE FOLDER FOUND
echo Drag and drop one or more update folder to run.
goto :exit

:no_batch_found
echo UPDATE NOT COMPLETED!
goto exit

:success
echo all updated has been run successfully
goto :exit

:exit
pause

Best Regards.


回答1:


You can sort your argument list right in your for loop like this:

setlocal enabledelayedexpansion
for /f "delims=" %%a in ('(for %%i in (%*^) do @echo %%~i^)^|sort') do (
    set dirname=%%a
    set dirname=!dirname:~0,-1!
    echo use "!dirname!" without the trailing space
)

P.S. It seems like sort appends a space to the end of string,(WTF ????) so you'll have to get rid of it. I changed the code.

Finally with the help of dbenham's explanation this becomes:

for /f "delims=" %%a in ('cmd /c "for %%i in (%*) do @echo %%~i"^|sort') do (
    echo use "%%a"
)

P.P.S This should work safer with commas in names (of course, they must be quoted)

for /f "delims=" %%a in ('cmd /c ^"for %%i in ^(%*^) do @echo %%~i^"^|sort') do (
        echo use "%%a"
)



回答2:


I would change the input set.

You can order by name by using /on and to get directories

/ad

so all directories by name =

dir /ad /on 


来源:https://stackoverflow.com/questions/10943099/how-to-sort-the-arguments-dropped-to-a-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!