Monthly Archives: October 2019

PowerShell

Powershell – Archive Log Files by Day

Log files, you have to love them because they allow you to figure out what’s going on but what do you do with them, by default they just keep writing and writing and at some point you need to do something with them.
I found this powershell script that can do exactly that and put it here for safe keeping

##############
# This script requires WMF version >= 5.0 -  Download WMF 5.1 from https://www.microsoft.com/en-us/download/details.aspx?id=54616
# The directory that has the files desired to be imported MUST HAVE TRAILING "\"
$path = "C:\onedrive_tt\Client\AbbVie\TCC_Touchpoints\doc\20190910-ResponseFiles\results\"
# Optional filter to only touch files with specified extension 
$mask = "*.csv" 
$ZipFileName= "CompressedBackup.zip"
#Filter to only touch files older than specified hours
$hours = 24
# Begin SMTP Server information 
# $SMTPPassword = "PlainText SMTP Password"
# $SMTPUser = "SMTP Authentication user, will also be SMTP From: address"
# $SMTPServer = "my.smtpserver.com"
# $SMTPTo = 'receive@myemail.com'
# $SMTPSubjectFail = "ZIP Folder script failed to run"
# $secpasswd = ConvertTo-SecureString $SMTPPassword -AsPlainText -Force
# $mycreds = New-Object System.Management.Automation.PSCredential($SMTPUser, $secpasswd)
# End SMTP Configuration
$problem = $false
$date = (Get-Date).tostring("yyyyMMdd")
#Pre setting error message to no issue, will change later in the script
$errorMessage="no issue"


#############


try {
    # Get all items from specified path, recursing into directories but not returning directories themselves. Excluding files with modificiation dates less than $hours
    $files = Get-ChildItem $path -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddHours(-$hours)) -and ($_.psIsContainer -eq $false)} 
    foreach ($file in $files) {
        $Directory = $path + $file.LastWriteTime.Date.ToString('yyyyMMdd')
        if (!(Test-Path $Directory)) {
	        New-Item $directory -type directory
	    }
	    Move-Item $file.fullname $Directory
    }
    $folders = Get-ChildItem $path -Directory  | % { $_.FullName }
    foreach ($folder in $folders) {
        $zipname = $folder + $ZipFileName
        if (!(test-path $zipname)){
        compress-archive -LiteralPath $folder -DestinationPath $zipname
        }
        if (test-path $zipname){
        remove-item -Recurse $folder 
        }
        else {
        Write-host $zipname + "Did not create, so I'm not deleting" + $folder
        }
    }
}
catch {
    $problem = $true
    $errormessage = $_.Exception.Message
}
finally {
    if ($problem){
        Write-Host $errorMessage
        # Send-MailMessage  -SmtpServer  $SMTPServer -UseSsl -From $SMTPUser -To $SMTPTo -Subject $SMTPSubjectFail  -Body $ErrorMessage -Credential $mycreds  
    }
    else {
        Write-Host "Script ran sucessfully"
    }
}