powershellbatch-filecmdrarwinrar

How to Compress a Folder That Changes name


I'm trying to compress a folder that changes name.

Example:

C:\202004
C:\202005
C:\202006
C:\202007

It keep creating a new folder as the months keep going by.

I wanna compress only the folder correspondent to the current month


Solution

  • Get some help from powershell's Get_date command:

    @echo off
    for /f "tokens=1 delims=" %%a in ('PowerShell -Command "& {Get-Date -format "yyyyMM"}"') do if exist "C:\%%a" echo C:\%%a
    

    Where you would replace echo C:\%%a with your actual compression command.

    a better method would be if you can test for the latest created folder and then compress that folder only.

    @echo off
    for /f "delims=" %%i in ('dir "c:\20*" /b /ad /o-d') do set "latest=%%i" & goto :comp
    :comp
    echo Zip/7z/rar "c:\%latest%" here
    

    Or we can combine the above by find the latest folder, then test if it is corresponding to the month, only then compress it:

    @echo off
    @echo off
    for /f "delims=" %%i in ('dir "c:\20*" /b /ad /o-d') do set "latest=%%i" & goto :comp
    :comp
    for /f "tokens=1 delims=" %%a in ('PowerShell -Command "& {Get-Date -format "yyyyMM"}"') do if "%%a" == "%latest%" echo Zip/7z/Rar C:\%latest% here