Powershell to zip folder & files, then delete old files
<p>I want to use Powershell to automate the: 
1. compression of log files (.xml and .dat extensions) older than 7 days, 
2. copy these compressed archives elsewhere and 
3. then delete the raw log files from source.</p>

<p>I am using the following Powershell script which I pieced together from various resources.</p>

<pre><code>function New-Zip
  {
   param([string]$zipfilename)
    set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipfilename).IsReadOnly = $false
  }

function Add-Zip
  {
   param([string]$zipfilename)

   if(-not (test-path($zipfilename)))
    {
    set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
    (dir $zipfilename).IsReadOnly = $false  
    }

  $shellApplication = new-object -com shell.application
  $zipPackage = $shellApplication.NameSpace($zipfilename)

   foreach($file in $input) 
     { 
        $zipPackage.CopyHere($file.FullName)
        Start-sleep -milliseconds 500
     }
   }

$targetFolder = 'C:\source'
$destinationFolder = 'D:\destination\'
$now = Get-Date
$days = 7
$lastWrite = $now.AddDays(-$days)

Get-ChildItem $targetFolder -Recurse | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
If ($_.LastWriteTime -lt $lastWrite)
{
    $_ | New-Zip $($destinationFolder + $_.BaseName + ".zip") 
    $_ | Add-Zip $($destinationFolder + $_.BaseName + ".zip")
}
}

Get-ChildItem $targetFolder -Recurse -Include "*.dat", "*.xml" | WHERE {($_.CreationTime -le $(Get-Date).AddDays(-$days))} | Remove-Item -Force
</code></pre>

<p>This script does work reasonably well, as it archives <strong>only</strong> the files, and copies them on destination folder. </p>

<p>If I have a structure of <strong>C:\source\bigfolder\logfile.dat</strong>, the resulting zip file will not get the folder structure as I would like: </p>

<p><strong>logfile.zip>bigfolder>logfile.dat</strong></p>

<p>Instead, it just gets: <strong>logfile.zip>logfile.dat</strong></p>

<p>Can someone help in figuring this out ?</p>

<p>To fine tune it even better, I would like if possible to build some logic, so the files are compressed only when a specific criteria is met.</p>

<p>The raw log files that I compress have a naming routine as following: </p>

<pre><code>Folders: 
  emstg#12_list\randomstring.xml

Individual log files:
  emstg#12_query_data.xml
  emstg#12_events_cache.dat etc... 
</code></pre>

<p>As you may see the start of these files is same with emstg#number.</p>

<p>How to implement a "name-detection" mechanism in script above ?</p>

<p>Thanks</p>