Introduction

This script was written to enable the backup of an application’s logs. The reason for this requirement is that the logs generated are overwritten between system or service restarts and we have a duty to maintain them for 5 years.

Input

| \# | Item | Required? | Description / Location | |---|---|---|---| | 1 | PARAMETER | yes | -folder <full path to target folder for compression> | | 2 | PARAMETER | yes | -zipfolder <full path to folder which will receive the zip file> |

Output

| \# | Item | Description / Location | |---|---|---| | 1 | LOG | All successful and failed operations will be logged in the log file defined by the script variable $LOG | | 2 | File Creation | If successful a new \*.zip file will be created in the -zipfolder <dir> defined by the caller |

Logging

Currently the logging is managed from within the script.

Log file location: C:\Scripts\Powershell\Logs\compress-archive.ps1.log

$LOGTIME is s timestamp in the format “yyyy-MM-dd_hh-mm-ss”

Log call within the script:
“$LOGTIME <<TEXT TO LOG>>” | Out-File $LOG -Append -Force

The script is then contained with a try{} catch{} parameter with logging output for all exception messages and items.

I’ve also tried to log throughout each action within the script so both SUCCESS and ERRORs are logged which provides a debugging method (at least I should know where it falls over!).

TODO; incorporate an email alert for all failures

Usage Examples

Contained in the header of the script – see below

The Script

As this script is running at the lowest privileges (ENG\svEngScript via Task Scheduler) I had to create a new GPO to permit that pre-existing account “Log on as batch job” via ticket #26725. I also had to them provide read permissions to the Cadence log file source on svlic1801 (C:\Cadence\Logfiles) along with read+write access to the target directory for the zip file at “C:\srvinstall\Cadence\CadenceLogFileBackup”. After these changes the user account was able to execute the powershell script successfully.

<pre class="wp-block-code">```
# Name : Compress Archive
# Author : Dave 
# Date : 
# Ticket# : 
#
#
# Scope : The source folder to be compressed and an output folder to receive the compressed file (both passed via parameters)
#
# Input(s) : Parameters[-folder <full path to folder>, -zipfolder <full path to zip output FOLDER>]
#
# Output(s) : A compressed .zip file of the [-folder] specified at the [-zipfolder] location specified
 
 
####################################################
# This script provides a controlled method of zipping a folder
####################################################
 
####################################################
# USAGE EXAMPLES
#
# Compress a folder:
# C:\> compressarchive.ps1 -folder "c:\test" -zipfolder "C:\zipped"
# EXPECTED OUTPUT:
# 1of2: A log entry at the defined $LOGFILEDIR\$LOGFILENAME confirming success of the compression in the format:
# [DATETIME STAMP] SUCCESS <path to the source folder> compressed to <path to the target output dir>\2019-03-08_154256_<source folder name>.zip
# 2of2: A new .zip file at <path to the target output dir>\2019-03-08_154256_<source folder name>.zip should exist
####################################################
 
# Define the required parameter of an input file (will need to be in CSV format with 3 columns: Hostname,IPAddress,VendorName - tested later in the script)
##################################################################################
param(
 [Parameter(Mandatory=$true)]
 [string]$folder,
  
 [Parameter(Mandatory=$true)]
 [string]$zipfolder
)
 
# Define the Variables
##################################################################################
$datetime = get-date -Uformat "%Y-%m-%d_%H%M%S"
##################################################################################
$LOGFILEDIR = "SOME DIRECTORY OF YOUR CHOICE" # the full path of the log file for the script to output to
$LOGFILENAME = "compressarchive.ps1.log" # the full name of the log file for the script to output to
$LOG = ($LOGFILEDIR + "\" + $LOGFILENAME)
$LOGTIME = Get-Date -Format "yyyy-MM-dd_hh-mm-ss"
 
# Prepare the logging
##################################################################################
# Check for the $LOGFILEDIR & $LOGFILENAME and create them if they don't exist
# NOTE: No logging until this happens except to STDOUT (Screen)
# Test for the folder and create if it doesn't exist:
Try
 {
 if(! (Test-Path -Path $LOGFILEDIR )){
 New-Item -ItemType directory -Path $LOGFILEDIR >$null
 }
 if(! (Test-Path $LOGFILEDIR\$LOGFILENAME )){
 New-Item -ItemType file -Path $LOGFILEDIR\$LOGFILENAME >$null
 }
 }
Catch
 {
 $ErrorMessage = $_.Exception.Message
 $FailedItem = $_.Exception.ItemName
 }
"$LOGTIME BEGIN SCRIPT" | Out-File $LOG -Append -Force
 
# Main
##################################################################################
Try {
    # examine the variable $folder and remove any trailing \'s
    if ($folder.substring($folder.length -1) -eq "\"){
        "$LOGTIME INFO $($folder) needs the trailing \ removed" | Out-File $LOG -Append -Force
        $folder = $folder.substring(0,$folder.length -1 )
        "$LOGTIME INFO $folder has been renamed to $($folder)" | Out-File $LOG -Append -Force
    } else {
        "$LOGTIME INFO $($folder) matches the required format" | Out-File $LOG -Append -Force
    }
     
    # check the directory exists
    if (test-path $folder -pathtype Any) {
        "$LOGTIME SUCCESS $($folder) exists on the filesystem" | Out-File $LOG -Append -Force
    } else {
        "$LOGTIME ERROR $($folder) does not exist on the filesystem, exiting" | Out-File $LOG -Append -Force
        exit
    }
     
    # examine the variable $zipfolder and remove any trailing \'s
    if ($zipfolder.substring($zipfolder.length -1) -eq "\"){
        "$LOGTIME INFO $($zipfolder) needs the trailing \ removed" | Out-File $LOG -Append -Force
        $zipfolder = $zipfolder.substring(0,$zipfolder.length -1 )
        "$LOGTIME INFO $zipfolder has been renamed to $($zipfolder)" | Out-File $LOG -Append -Force
    } else {
        "$LOGTIME INFO $($zipfolder) matches the required format" | Out-File $LOG -Append -Force
    }
     
    # check the directory exists
    if (test-path $zipfolder -pathtype Any) {
        "$LOGTIME SUCCESS $($zipfolder) exists on the filesystem" | Out-File $LOG -Append -Force
    } else {
        "$LOGTIME ERROR $($zipfolder) does not exist on the filesystem, exiting" | Out-File $LOG -Append -Force
        exit
    }
     
    # create a unique filename $zip_file_name for the zip using the $datetime variable as part of the file
    # (eg: C:\output\2019-03-07_113010_logfiles.zip
    # where $zipfolder = c:\output and $folder = c:\someapplication\logfiles
    $zip_file_name = split-path $folder -leaf
    $zipfilepath = "$zipfolder\$datetime`_$zip_file_name.zip"
    "$LOGTIME SUCCESS `$zipfilepath assigned to '$($zipfilepath)' " | Out-File $LOG -Append -Force
     
    # compress the $folder outputting it to $zipfilepath and leaving the original folder in place
    compress-archive -path $folder -CompressionLevel Optimal -DestinationPath $zipfilepath
    "$LOGTIME SUCCESS $folder compressed to $($zipfilepath)" | Out-File $LOG -Append -Force
}
 
Catch {
 $ErrorMessage = $_.Exception.Message
 $FailedItem = $_.Exception.ItemName
 "$LOGTIME ERROR $($ErrorMessage) $($FailedItem)" | Out-File $LOG -Append -Force #LOGACTION
 }

```