# encoding: ascii
# api: powershell
# title: Zip database trace files
# description: I wrote this scrip to find and zip database trace files. There are switch parameters to search subdirectories recursively as well as removing the original trace file.
# version: 0.1
# type: function
# author: Kevin Bullen
# license: CC0
# function: Zip-TraceFiles
# x-poshcode-id: 3672
# x-archived: 2012-10-21T16:42:43
# x-published: 2012-10-01T12:01:00
#
#
Clear-Host
function Zip-TraceFiles {
Param(
[string]$DirToSearch,
[switch]$SearchSubDirs,
[switch]$RemoveTraceFile
)
# search the dirs for .trc files
If ($SearchSubDirs -eq -$true) {
$TraceFiles = Get-ChildItem -Path $DirToSearch | Where-Object {$_.Extension -eq '.trc'};
}
else {
$TraceFiles = Get-ChildItem -Path $DirToSearch -Recurse | Where-Object {$_.Extension -eq '.trc'};
}
If ($TraceFiles -ne $null) {
ForEach($TraceFile in $TraceFiles)
{
$FullTraceFile = $($TraceFile.Directory.ToString() + "\" + $TraceFile.Name);
Write-Host "Zipping File $FullTraceFile";
$NewZipFile = $FullTraceFile;
If (-not $NewZipFile.EndsWith('.zip')) {
$NewZipFile += '.zip';
}
If (Test-Path -path $NewZipFile -PathType Leaf) {
Remove-Item -path $NewZipFile -Force;
}
# code from David Aiken
# http://blogs.msdn.com/b/daiken/archive/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget.aspx
# http://stackoverflow.com/questions/5230886/please-explain-set-content-zipfilename-pk-char5-char6-char0
Set-Content $NewZipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18));
try {
$ZipFile = (New-Object -com shell.application).NameSpace($NewZipFile);
$FileToZip = Get-Item -path $FullTraceFile
$ZipFile.CopyHere( $FileToZip.fullname );
$size = $ZipFile.Items().Item($FileToZip.Name).Size;
While($ZipFile.Items().Item($FileToZip.Name) -eq $null)
{
Start-Sleep -Seconds 1;
Write-Host "." -NoNewline;
}
Write-Host ".";
# remove trc file
If ($RemoveTraceFile -eq $true) {
If (Test-Path -path $FullTraceFile -PathType Leaf) {
Remove-Item -path $FullTraceFile -Force;
}
}
}
catch {
Write-Host $_.Exception.ToString()
} # try catch
} # ForEach
} # $TraceFiles -ne $null
}
Zip-TraceFiles -DirToSearch 'C:\TEMP\_psdev' -SearchSubDirs -RemoveTraceFile