我需要编写一个 powershell 脚本,使用 windows 内置的压缩方法压缩所有日志文件。这是我目前所拥有的:
#declare functions here
function new-zipfile {
param ($zipfile)
if (! $zipfile.endswith('.zip')) {$zipfile += '.zip'}
set-content $zipfile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfile).IsReadOnly = $false
}
#define variables here
#some strings and numbers we will need
$thismonthint = get-date -f "MM"
$prevmonthint = (get-date).addmonths(-1).tostring("MM")
$thismonthstr = get-date -f "MMM"
$prevmonthstr = (get-date).addmonths(-1).tostring("MMM")
$thisyearlongint = get-date -f "yyyy"
$thisyearshortint = get-date -f "yy"
$thislogdir = 'C:\rad\'
$thiszipfile = $thislogdir + $prevmonthstr + $thisyearlongint + '.zip'
$zipexists = test-path $thiszipfile
#start program here
#first pass, check for .zip files of previous months. if exists exit. if not exist, create empty .zip file
if (! $zipexists)
{
echo 'zip file does not exist, creating zip file'
new-zipfile $thiszipfile
}
else
{
return
}
# move all log files where the month number matches the month number of the .zip file
# Jan = 01, Feb = 02, Mar =03 etc. etc.
foreach ($file in Get-ChildItem $thislogdir)
{
zipfile = (New-Object -ComObject shell.application).NameSpace($thiszipfile)
$zipfile.MoveHere($file.fullname)
Start-Sleep -Seconds 120
Move-Item 'c:\rad\*.txt' new-zipfile
}