How to copy last but one modified file using batch file/powershell?

For example I have 4 folders and I want to copy only Last but one modified folder. Is there a way to copy only one folder instead of all the folders? Currently I using batch file to copy paste last modified file as shown below:

FOR /F "delims=" %%i IN ('dir "Sourcedir"/b /ad-h /t:c /od') DO SET a=%%i
echo Most recent subfolder: %a%
pause
xcopy "Destinationdir" "Sourcedir\%a%\" /o /x /e /h /k

2 answers

  • answered 2018-11-08 06:29 npocmaka

    try like this:

    @echo off
    setlocal enableDelayedExpansion
    FOR /F "delims=" %%i IN ('dir "." /b /ad-h /t:c /od') DO (
     set "prev=!last!"
     set "last=%%i"
    )
    
    echo %prev%
    

  • answered 2018-11-08 07:26 Compo

    You may wish to try something along these lines:

    @Echo Off
    Set "Directory="
    For /F "Skip=1 Delims=" %%A In ('Dir /B /AD /O-D /TW "Sourcedir"'
    ) Do Set "Directory=%%A" & GoTo :CopyIt
    :CopyIt
    If Defined Directory XCopy "SourceDir\%Directory%" "DestinationDir\" /E /H /X /Y