【发布时间】:2020-07-20 18:30:13
【问题描述】:
我正在尝试压缩更改名称的文件夹。
例子:
C:\202004
C:\202005
C:\202006
C:\202007
随着时间的推移,它会不断创建一个新文件夹。
我只想压缩当前月份对应的文件夹
【问题讨论】:
标签: powershell batch-file cmd rar winrar
我正在尝试压缩更改名称的文件夹。
例子:
C:\202004
C:\202005
C:\202006
C:\202007
随着时间的推移,它会不断创建一个新文件夹。
我只想压缩当前月份对应的文件夹
【问题讨论】:
标签: powershell batch-file cmd rar winrar
从powershell 的Get_date 命令获得一些帮助:
@echo off
for /f "tokens=1 delims=" %%a in ('PowerShell -Command "& {Get-Date -format "yyyyMM"}"') do if exist "C:\%%a" echo C:\%%a
您可以将echo C:\%%a 替换为您的实际压缩命令。
如果您可以测试最新创建的文件夹,然后仅压缩该文件夹,则更好的方法是。
@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
或者我们可以结合上面找到最新的文件夹,然后测试是否对应月份,然后压缩:
@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
【讨论】:
如果你有 powershell 5+
$date = Get-Date -Format "yyyyMM"
Compress-Archive -Path "c:\$date\" -DestinationPath "c:\$date.zip"
【讨论】:
我看到您已经选择了一个答案。能够在当月之外压缩目录可能会很好。如果存档文件不存在,此代码将压缩所有这些文件。默认只压缩当前月份。
=== 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
}
}
}
调用它以仅压缩当前月份,使用:
powershell -NoLogo -NoProfile -File .\Compress-MonthlyFiles.ps1
如果它们尚不存在,则为所有月份制作存档文件:
powershell -NoLogo -NoProfile -File .\Compress-MonthlyFiles.ps1 -AllMonths
【讨论】: