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
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
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
If you have powershell 5+
$date = Get-Date -Format "yyyyMM"
Compress-Archive -Path "c:\$date\" -DestinationPath "c:\$date.zip"
I see that you have already selected an answer. It might be good to be able to compress a directory outside of the current month. This code will compress all of them if an archive file does not exist. By default, it will only compress the current month.
=== Compress-MonthlyFiles.ps1
#Requires -Version 5
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[switch]$AllMonths = $false
)
$BaseDir = 'C:\src\t'
$CompDir = 'C:\src\t\Compressed\Months'
$DirFilter = if ($AllMonths) { '??????' } else { Get-Date -Format 'yyyyMM'}
Get-ChildItem -Directory -Path $BaseDir -Filter $DirFilter |
ForEach-Object {
# Check to see that the directory name is exactly six (6) digits
if ($_.Name -match '^\d{6}$') {
$ArchiveFilename = Join-Path -Path $CompDir -ChildPath "$($_.Name).zip"
# If the archive file does not exist, create it
if (-not (Test-Path -Path $ArchiveFilename)) {
Compress-Archive -Path $_.FullName -DestinationPath $ArchiveFilename
}
}
}
Invoke it to compress only the current month using:
powershell -NoLogo -NoProfile -File .\Compress-MonthlyFiles.ps1
Make archive files for all months if they do not already exist using:
powershell -NoLogo -NoProfile -File .\Compress-MonthlyFiles.ps1 -AllMonths