Deleting the old print job files

This script finding old print job files in Print Server print job log path, moving them to backup folder and finaly deleting the old print job files. This script contains logging and e-mail messaging. Attention! This script do not contains interactive messages and don’t need user actions! Before using the script check e-mail messaging by powershell cmdlet Send-MailMessage (look at Microsoft Docs) Script only for ENG and RU locales Attention! Minimal PowerShell version 5.0 version 1.1
HowOldPrintFiles It’s integer parameter. How old (days) must be print job files in Print Server for removing
HowOldBackupFiles It’s integer parameter. How old (days) must be print job files in BACKUP FOLDER for removing
BackupPath It’s string parameter. Backup folder path. Example “\\server02\Print_Job_Backup”
MailTo E-mail for results sending. Example: “JohnRico@starship.troopers.com” or @(JohnRico@starship.troopers.com, LukeSkywalker@star.wars.com)
MailFrom It’s string parameter. E-mail ‘from’ sender. Example: “JeanRasczak@starship.troopers.com”
SMTPServer It’s string parameter. SMTP-server NetBIOS name or FQDN. Example: “mail.starship.troopers.com”

Example
Delete_print_job_files_common.ps1 -HowOldPrintFiles 14 -HowOldBackupFiles 62 -BackupPath “\\server02\Print_Job_Backup” -AdminMail “LukeSkywalker@star.wars.com”

<# .SYNOPSIS Deleting print job files .DESCRIPTION This script finding old print job files in Print Server print job log path, moving them to backup folder and finaly deleting the old print job files. This script contains logging and e-mail messaging. Attention! This script do not contains interactive messages and don't need user actions! Attention! Before using the script check e-mail messaging by powershell cmdlet Send-MailMessage (look at Microsoft Docs) Attention! Script only for ENG and RU locales Attention! Minimal PowerShell version 5.0 version 1.1 .PARAMETER HowOldPrintFiles It's integer parameter. How old (days) must be print job files in Print Server for removing .PARAMETER HowOldBackupFiles It's integer parameter. How old (days) must be print job files in BACKUP FOLDER for removing .PARAMETER BackupPath It's string parameter. Backup folder path. Example "\\server02\Print_Job_Backup" .PARAMETER MailTo E-mail for results sending. Example: "JohnRico@starship.troopers.com" or @(JohnRico@starship.troopers.com, LukeSkywalker@star.wars.com) .PARAMETER MailFrom It's string parameter. E-mail 'from' sender. Example: "JeanRasczak@starship.troopers.com" .PARAMETER SMTPServer It's string parameter. SMTP-server NetBIOS name or FQDN. Example: "mail.starship.troopers.com" .EXAMPLE Delete_print_job_files_common.ps1 -HowOldPrintFiles 14 -HowOldBackupFiles 62 -BackupPath "\\server02\Print_Job_Backup" -AdminMail "LukeSkywalker@star.wars.com" #>
Param (
    [PARAMETER (Mandatory=$true)][int]$HowOldPrintFiles,
    [PARAMETER (Mandatory=$true)][int]$HowOldBackupFiles,
    [PARAMETER (Mandatory=$true)][string]$BackupPath,
    [PARAMETER (Mandatory=$true)]$MailTo,
    [PARAMETER (Mandatory=$true)]$MailFrom,
    [PARAMETER (Mandatory=$true)]$SMTPServer
)
#VARIABLES
#
#$WhatIfPreference = $true
#You can uncomment $WhatifPreference for testing script.Choose switch parameter $true fo testing $false for production enviroment
#
$SourceEventName = "My Scripts"#Name of new Source for Windows EventLog
#
$ScriptName = $MyInvocation.MyCommand.Name
$ScriptInfo = $MyInvocation.MyCommand.Path
#
$PSEmailServer = $SMTPServer
#
$Now = Get-Date
$TodaySimpleDate = Get-Date -UFormat %Y.%m.%d
#
$LastWritePrintFolder = $Now.AddDays(-$HowOldPrintFiles)
$LastWriteBackupFolder = $Now.AddDays(-$HowOldBackupFiles)
#
$HostName = $env:COMPUTERNAME
$ScriptLogFileDirectory = "$env:SystemDrive\Scripts\Logs"
$ScriptLogFile = "$env:SystemDrive\Scripts\Logs\$TodaySimpleDate-Print_Job_deleting_log.log"
#
$PathPrintJobFolder = "C:\Windows\System32\spool\PRINTERS" #Print job files folder
$PathBackupFolder = $BackupPath #Backup folder path
$FinalyBackupFolder = "$PathBackupFolder\$HostName\$TodaySimpleDate\PRINTERS"
#
$AddFolderError = "No errors"
$AddContentError = "No errors"
$WriteEventLogError = "No errors"
$GetEventLogMessageError = "No errors"
$PrintJobFolderError = "No errors"
$BackupFolderError = "No errors"
$FinalyBackupFolderError = "No errors"
#
$CopyError = $false
$DelError = $false
$ItemDelError = $false
#
#FUNCTIONS
#
Function LogWrite
{
 <# .SYNOPSIS Writing actions and warnings to file. .DESCRIPTION This function writes some warnings and actions to log file. The function uses variable $ScriptLogFile from main script. .PARAMETER Logstring Text string to log file .EXAMPLE LogWrite "This message will written to $ScriptLogFile with date-time before text" #>
Param ([string]$Logstring)
$DateWrite = Get-Date -Format FileDateTime
$EntryLine = "$DateWrite $logstring" #Add date-time to line on the log files
Add-Content $ScriptLogFile -Value $EntryLine
}
#
Function EventLogWrite
{
 <# .SYNOPSIS Writing actions and warnings to Windows EventLog. .DESCRIPTION This function writes some warnings and actions to Windows EventLog, type Application. .PARAMETER EventMessage Text string to log file .PARAMETER EventType Type of message (error, information etc) See EventLogEntryType in Microsoft Dosc .EXAMPLE EventLogWrite -EventMessage "This message will written to Windows EventLog name Application" -EventType "Error" #>
Param (
    [PARAMETER(Mandatory=$true)][string]$EventMessage,
    [PARAMETER(Mandatory=$true)][System.Diagnostics.EventLogEntryType]$EventType)
$DateWrite = Get-Date -Format FileDateTime
$EventMessageLine = "$DateWrite $EventMessage"
Write-EventLog -LogName Application -EntryType $EventType -Message $EventMessageLine -EventId "0" -Category "0" -Source $SourceEventName
}
#
Function CopyDeleteFile
{
 <# .SYNOPSIS Function for script .DESCRIPTION It's typical action for backup and remove old files .PARAMETER FileToActions File from files array or alone file .PARAMETER DestinationFolder Folder path for backup .EXAMPLE CopyDeleteFile -FileToActions $File1 -DestinationFolder $PathForBackup #>
Param (
    [PARAMETER(Mandatory=$true)]$FileToActions,
    [PARAMETER(Mandatory=$true)]$DestinationFolder)
#
LogWrite "Copying file $FileToActions to $DestinationFolder ...";
Copy-Item $FileToActions -Destination $DestinationFolder -ErrorVariable CopyItemError -ErrorAction SilentlyContinue # Copy files to Backup Folder before deleting
If ($? -eq $true)
{
    LogWrite "File $FileToActions is copied to $DestinationFolder";
    LogWrite "Deleting file $FileToActions from Print Server...";
    $null = Remove-Item $FileToActions -ErrorVariable RemoveItemError -ErrorAction SilentlyContinue #Delete files from Server
    If ($? -eq $true)
    {
        LogWrite "$FileToActions is deleted from Print Server"
    }
    Else
    {
        LogWrite "ERROR! Can't delete file $FileToActions! File is left on the Print Server!"
        LogWrite $RemoveItemError
        $DeletingFileError = $true
    }
}
Else
{
    LogWrite "ERROR! Can't copy file $FileToActions! Deleting is stopped! File is left on the Print Server!"
    LogWrite $CopyItemError
    $CopyingFileError = $true
}
If ($CopyingFileError -eq $true)
{
    Return "Copying Error"
}
If ($DeletingFileError -eq $true)
{
    Return "Deleting Error"
}
}
#
#
Function ItemDelete
{
 <# .SYNOPSIS Function for script .DESCRIPTION It's typical action for delete files and folders .PARAMETER ItemToActions File or folder for deleting .EXAMPLE ItemDelete -ItemToActions $File1 #>
Param ([PARAMETER(Mandatory=$true)]$ItemToActions)
#
LogWrite "Deleting item $($ItemToActions.FullName)...";
$null = Remove-Item $ItemToActions.FullName -ErrorVariable RemItemError -ErrorAction SilentlyContinue # Deleting item
If ($? -eq $true)
{
    LogWrite "$($ItemToActions.FullName) was deleted"
}
Else
{
    LogWrite "ERROR! Can't delete item $($ItemToActions.FullName)! Item is left on the Server!"
    LogWrite $RemItemError
    $DeletingItemError = $true
}
If ($DeletingItemError -eq $true)
{
    Return "Deleting Item Error"
}
}
#
#TESTS BEGIN
#
#CHECK RIGTHS FOR SCRIPT LOG FOLDER AND FOR WRITING
#
If (Test-Path -Path "$env:SystemDrive\Scripts\Logs")
{
    Add-Content $ScriptLogFile -Value "$(Get-Date -Format FileDateTime) Script $ScriptInfo is started" -ErrorAction SilentlyContinue
    Add-Content $ScriptLogFile -Value "$(Get-Date -Format FileDateTime) Test 'CHECK RIGTHS FOR SCRIPT LOG FOLDER AND FOR WRITING' passed" -ErrorVariable AddContentError -ErrorAction SilentlyContinue
    If ($? -eq $false)
    {
        $IsAddContentToScriptLogFileError = $true;
    }
}
Else
{
    $null = New-Item -ItemType Directory -Path "$env:SystemDrive\Scripts\Logs" -ErrorVariable AddFolderError -ErrorAction SilentlyContinue
    If ($? -eq $true)
    {
        Add-Content $ScriptLogFile -Value "$(Get-Date -Format FileDateTime) Script $ScriptInfo is started";
        Add-Content $ScriptLogFile -Value "$(Get-Date -Format FileDateTime) Test 'CHECK RIGTHS FOR SCRIPT LOG FOLDER AND FOR WRITING' is started" -ErrorVariable AddContentError
        If ($? -eq $false)
        {
            $IsAddContentToScriptLogFileError = $true;
        }
    }
    Else
    {
        $IsAddNewFolderForScriptLogFileError = $true;
    }
}
If ($IsAddNewFolderForScriptLogFileError -eq $true -or $IsAddContentToScriptLogFileError -eq $true)
{
    Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script Execution Error on $HostName" -Encoding ([System.Text.Encoding]::UTF8) -Body "Script $ScriptInfo Execution Error on $HostName!!!`nScript execution was stoped!!!`n***`nAdding new folder for log error:`n$AddFolderError`n***`nAdding content to log file error:`n$AddContentError";
    Exit
}
Else
{
    LogWrite "Test 'CHECK RIGTHS FOR SCRIPT LOG FOLDER AND FOR WRITING' passed"
}
#
#CHECK CREATING NEW SOURCE IN THE WINDOWS EVENTLOG
#
LogWrite "Test 'CHECK CREATING NEW SOURCE IN THE WINDOWS EVENTLOG' started";
$null = New-EventLog -LogName Application -Source $SourceEventName -ErrorVariable NewEventLogSourceError -ErrorAction SilentlyContinue
If ($? -eq $true)
{
    LogWrite "New EventLog Source 'My Scripts' was created on the server $HostName without errors";
    LogWrite "Test 'CHECK CREATING NEW SOURCE IN THE WINDOWS EVENTLOG' passed";
}
Else
{
    If ($NewEventLogSourceError -like "уже зарегистрирован на компьютере" -or "source is already registered")
    {
        LogWrite "EventLog Source 'My Scripts' is already registered on the server $HostName";
        LogWrite "Test 'CHECK CREATING NEW SOURCE IN THE WINDOWS EVENTLOG' passed";
    }
    Else
    {
        LogWrite "ERROR! Creating Windows EventLog Source on the server $HostName finished with error $NewEventLogSourceError";
        LogWrite "Test 'CHECK CREATING NEW SOURCE IN THE WINDOWS EVENTLOG' failed";
        LogWrite "Script execution will canceled after e-mail message";
        LogWrite "Sending message to $MailTo ..."
        Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script Execution Error on $HostName" -Encoding ([System.Text.Encoding]::UTF8) -Body "Script $ScriptInfo Execution Error on $HostName!!!`nScript execution was stoped!!!`n***`nAdding new EventLog Source error:`n$NewEventLogSourceError" -Attachments $ScriptLogFile
        If ($? -ne $true) 
        {
            LogWrite "ERROR! Message wasn't sended!"
        }
        Exit
    }
}
#
#CHECK RIGHTS FOR WRITING TO WINDOWS EVENTLOG
#
LogWrite "Test 'CHECK RIGHTS FOR WRITING TO WINDOWS EVENTLOG' started";
$DateTimeForWriting = Get-Date -Format FileDateTime
Write-EventLog -LogName Application -EntryType Information -EventId 1 -Source "My Scripts" -Message "$DateTimeForWriting Check rights for writing to Windows EventLog" -ErrorVariable WriteEventLogError
If ($? -eq $true)
{
    $EventFromEventLog = Get-EventLog Application -Message "$DateTimeForWriting Check rights for writing to Windows EventLog" -ErrorVariable GetEventLogMessageError
    If ($? -eq $true -and $EventFromEventLog -ne $null)
    {
        LogWrite "Test 'CHECK RIGHTS FOR WRITING TO WINDOWS EVENTLOG' passed";
    }
    Else
    {
        LogWrite "ERROR! Getting Windows EventLog Message on the server $HostName finished with error $GetEventLogMessageError";
        $IsGetEventLogMessageError = $true
    }
}
Else
{
    $IsWriteEventLogError = $true
}
If ($IsWriteEventLogError -eq $true -or $IsGetEventLogMessageError -eq $true)
{
    LogWrite "Test 'CHECK RIGHTS FOR WRITING TO WINDOWS EVENTLOG' failed";
    LogWrite "Script execution will canceled after e-mail message";
    LogWrite "Sending message to $MailTo ..."
    Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script Execution Error on $HostName" -Encoding ([System.Text.Encoding]::UTF8) -Body "$Script ScriptInfo Execution Error on $HostName!!!`nScript execution was stoped!!!`n***`nWriting to Windows EventLog error:`n$WriteEventLogError`n***`nGetting message from Wondows EventLog error:`n$GetEventLogMessageError"
    If ($? -ne $true) 
    {
        LogWrite "ERROR! Message wasn't sended!"
    }
    Exit
}
#TESTS END
#
#BODY
#
LogWrite "Script BODY execution started"
EventLogWrite -EventType Information -EventMessage "$ScriptName TESTS passed. $ScriptInfo Script BODY execution started!"
#
If ($(Test-Path -Path $PathPrintJobFolder) -eq $true)
{
    If ($(Test-Path -Path $PathBackupFolder) -eq $true)
    {
        If ($(Test-Path -Path $FinalyBackupFolder) -eq $true)
        {
            $Files1 = Get-ChildItem $PathPrintJobFolder -Include "*.SPL", "*.SHD" -Recurse | Where LastWriteTime -le $LastWritePrintFolder
            foreach ($File1 in $Files1)
            {
                $ResultCopyDeleteFunctionError = CopyDeleteFile -FileToActions $File1 -DestinationFolder $FinalyBackupFolder #Using function CopyDeleteFile
                If ($ResultCopyDeleteFunctionError -eq "Deleting Error")
                {
                    $DelError = $true
                }
                If ($ResultCopyDeleteFunctionError -eq "Copying Error")
                {
                    $CopyError = $true
                }
            }
            Logwrite "Copying from server was finished"
            Logwrite "Starting deleting old files..."
            $Files2 = Get-ChildItem "$PathBackupFolder\$HostName\" -Include "*.SPL", "*.SHD" -Recurse | Where LastWriteTime -le $LastWriteBackupFolder
            foreach ($File2 in $Files2)
            {
                $ResultItemDeleteFunctionAction = ItemDelete -ItemToActions $File2 #Delete items from Backup Folder using function ItemDelete
                If ($ResultItemDeleteFunctionAction -eq "Deleting Item Error") 
                {
                    $ItemDelError = $true
                }
            }
            Logwrite "Deleting files from backup server was finished"
            Logwrite "Starting deleting old folders..."
            $Folders = Get-ChildItem "$PathBackupFolder\$HostName\" -Directory | Where CreationTime -le $LastWriteBackupFolder 
            foreach ($Folder in $Folders) 
            {
                $ResultItemDeleteFunctionAction = ItemDelete -ItemToActions $Folder #Delete items from Backup Folder using function ItemDelete
                If ($ResultItemDeleteFunctionAction -eq "Deleting Item Error") 
                {
                    $ItemDelError = $true
                }
            }
        }
        Else
        {
            $null = New-Item -Path $FinalyBackupFolder -ItemType Directory -ErrorVariable NewItemFinalyBackupFolderError -ErrorAction SilentlyContinue;
            If ($? -eq $true)
            {
                $Files1 = Get-ChildItem $PathPrintJobFolder -Include "*.SPL", "*.SHD" -Recurse | Where LastWriteTime -le $LastWritePrintFolder
                foreach ($File1 in $Files1)
                {
                    $ResultCopyDeleteFunctionError = CopyDeleteFile -FileToActions $File1 -DestinationFolder $FinalyBackupFolder #Using function CopyDeleteFile
                    If ($ResultCopyDeleteFunctionError -eq "Deleting Error")
                    {
                        $DelError = $true
                    }
                    If ($ResultCopyDeleteFunctionError -eq "Copying Error")
                    {
                        $CopyError = $true
                    }
                }
                Logwrite "Copying from server was finished"
            Logwrite "Starting deleting old files..."
                $Files2 = Get-ChildItem "$PathBackupFolder\$HostName\" -Include "*.SPL", "*.SHD" -Recurse | Where LastWriteTime -le $LastWriteBackupFolder
                foreach ($File2 in $Files2)
                {
                    $ResultItemDeleteFunctionAction = ItemDelete -ItemToActions $File2
                    If ($ResultItemDeleteFunctionAction -eq "Deleting Item Error") 
                    {
                        $ItemDelError = $true
                    }
                }
                Logwrite "Deleting files from backup server was finished"
            Logwrite "Starting deleting old folders..."
                $Folders = Get-ChildItem "$PathBackupFolder\$HostName\" -Directory | Where CreationTime -le $LastWriteBackupFolder 
                foreach ($Folder in $Folders) 
                {
                    $ResultItemDeleteFunctionAction = ItemDelete -ItemToActions $Folder
                    If ($ResultItemDeleteFunctionAction -eq "Deleting Item Error") 
                    {
                        $ItemDelError = $true
                    }
                }
            }
            Else
            {
                $FinalyBackupFolderError = $NewItemFinalyBackupFolderError
                LogWrite "ERROR! Path $FinalyBackupFolder was not created! Check the script rigts for paths!";
                LogWrite "$NewItemFinalyBackupFolderError"
                $IsFinalyBackupFolderError = $true
            }
        }
    }
    Else
    {
        LogWrite "ERROR! Path $PathBackupFolder does not exist! Check the paths!";
        $BackupFolderError = "Path $PathBackupFolder does not exist! Check the paths!"
        $IsPathBackupFolderError = $true
    }
}
Else
{
    LogWrite "ERROR! Path $PathPrintJobFolder does not exist! Check the paths!";
    $PrintJobFolderError = "Path $PathPrintJobFolder does not exist! Check the paths!"
    $IsPathPrintJobFolderError = $true
}
LogWrite "Script BODY execution is finished"
#
#END
#
LogWrite "Script END execution is started"
If ($IsPathPrintJobFolderError -eq $true -or $IsPathBackupFolderError -eq $true -or $IsFinalyBackupFolderError -eq $true)
{
    LogWrite "ERROR! Global error in script is found! Check log-file"
    LogWrite "Adding info to Windows EventLog..."
    EventLogWrite -EventType Error -EventMessage "ERROR! Global error in script $ScriptInfo is found! Check mailbox $MailTo and log-file $ScriptLogFile"
    LogWrite "Script END execution is finished"
    LogWrite "Script execution is finished WITH GLOBAL errors"
    LogWrite "Sending message to $MailTo ..."
    Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script Execution ERROR on $HostName" -Attachments $ScriptLogFile -Encoding ([System.Text.Encoding]::UTF8) -Body "Script $ScriptInfo Execution Error on $HostName!!!`nScript execution was stoped!!!`n***`nPath Print Server Folder error:`n$PrintJobFolderError`n***`nPath Backup Folder error:`n$BackupFolderError`n***`nPath Finaly Backup Folder error:`n$FinalyBackupFolderError"
    If ($? -ne $true) 
    {
        LogWrite "ERROR! Message wasn't sended!"
    }
    Exit
}
If ($CopyError -eq $true -or $DelError -eq $true -or $ItemDelError -eq $true)
{
    LogWrite "Some errors are found! Check log!"
    LogWrite "Adding info to Windows EventLog..."
    EventLogWrite -EventType Warning -EventMessage "WARNING! Some errors are found in script $ScriptInfo! Check mailbox $MailTo and log-file $ScriptLogFile"
    LogWrite "Script END execution is finished"
    LogWrite "Script execution is finished WITH some errors"
    LogWrite "Sending message to $MailTo ..."
    Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script execution was successful on $HostName WITH errors" -Body "$Script $ScriptInfo on $HostName was finished WITH SOME errors.`nResults are in the attachment and on the server $HostName in file $ScriptLogFile." -Encoding ([System.Text.Encoding]::UTF8) -Attachments "$ScriptLogFile"#Send final message to ADMIN
    If ($? -ne $true) 
    {
        LogWrite "ERROR! Message wasn't sended!"
    }
    Exit
}
Else
{
    LogWrite "Script END execution is finished"
    LogWrite "Script execution is finished WITHOUT errors"
    EventLogWrite -EventType Information -EventMessage "Script $ScriptInfo on $HostName was finished WITHOUT errors! For information look at mailbox $MailTo and log-file $ScriptLogFile"
    Send-MailMessage -From $MailFrom -To $MailTo -Subject "Script execution was successful on $HostName WITHOUT errors" -Body "Script $ScriptInfo on $HostName was finished WITHOUT errors.`nResults are in the attachment and on the server $HostName in file $ScriptLogFile." -Encoding ([System.Text.Encoding]::UTF8) -Attachments "$ScriptLogFile"#Send final message to ADMIN
    If ($? -ne $true) 
    {
        LogWrite "ERROR! Message wasn't sended!"
    }
}
#
Exit
#

Leave a Reply