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
On
If you have powershell 5+
$date = Get-Date -Format "yyyyMM"
Compress-Archive -Path "c:\$date\" -DestinationPath "c:\$date.zip"
On
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
Get some help from
powershell'sGet_datecommand:Where you would replace
echo C:\%%awith your actual compression command.a better method would be if you can test for the latest created folder and then compress that folder only.
Or we can combine the above by find the latest folder, then test if it is corresponding to the month, only then compress it: