我正在尝试创建脚本来列出日志,然后每月压缩它并将其放在同一目录中。我们在 C:\TestLogs\ 示例脚本中有许多日志子文件夹,我有
# set folder path
$log_path = "C:\TestLogs\"
$7zip_path = "C:\7z\7za.exe"
# set min age of files
$max_days = "-30"
# get the current date
$curr_date = Get-Date
# determine how far back we go based on current date
$zip_date = $curr_date.AddDays($max_days)
# filter files
Get-ChildItem $log_path -Recurse | Where-Object { ($_.LastWriteTime -lt
$zip_date) -and ($_.psIsContainer -eq $false)} |
ForEach {
$Zip = $log_path + "{0:MMM}_{0:yyyy}.zip" -f $_.LastWriteTime
& $7zip_path u -tzip $Zip $_.FullName |Out-Null
}
结果是它仅在 C:\TestLogs\ 中创建 Mar_2018.zip 等,如何在子文件夹内创建 zip,如 C:\TestLogs\logbakcup\Mar_2018.zip 或 C:\TestLogs\Runtime log\April_2017.zip 或 C:\TestLogs\logbackup\January\January_2017.zip
答案1
我不太了解 7zip 实用程序的语法,但您可以尝试使用本机 powershell 命令 Compress-Archive。如下所示:
#set folder path
$log_path = "C:\TestLogs\"
$7zip_path = "C:\7z\7za.exe"
#set min age of files
$max_days = "-30"
#get the current date
$curr_date = Get-Date
#determine how far back we go based on current date
$zip_date = $curr_date.AddDays($max_days)
#filter files
[array]$folders = Get-ChildItem $log_path | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false)}
ForEach ($subfolder in $folders) {
$subfolderLastWriteTime = Get-Date $subfolder.LastWriteTime -Format 'dd.MM.yyyy'
$DestPath = $subfolder.Fullname + '\' + $subfolderLastWriteTime
Compress-Archive -Path $subfolder.FullName -DestinationPath "$DestPath.zip"
}