HEX
Server: Microsoft-IIS/10.0
System: Windows NT ITPWINWEBSVR22 10.0 build 20348 (Windows Server 2022) AMD64
User: www.conferencesearch.co.uk (0)
PHP: 8.3.30
Disabled: NONE
Upload Files
File: D:/bin/scripts/PowerShell/IISLogArchive.ps1
# (SS,18/09/23) IIS Log Archive
# (SS,19/11/23) Finished and made live,

# with help from
# https://techblogs.42gears.com/how-to-compress-zip-files-older-than-x-days-and-delete-the-original-files-post-compression-using-power-shell-script/

#. D:\Bin\Scripts\Utils.ps1
. D:\Bin\Scripts\PowerShell\Utils.ps1

$SourcePath = "D:\IISLogFiles\"
#$SourcePath = "D:\IISLogFilesCopy\"
#$ArchivePath = "E:\IISLogArchive\"
$ArchivePath = "T:\IIS Logs Archive\"
$DrivesToCheck = "C,D,T"

$NEW_LINE = "`r`n"
$result = ""

$result = "Started " + (Get-Date).ToString("dd-MM-yyyy HH:mm:ss") + $NEW_LINE
#$result += Get-Date
#$result += $NEW_LINE
#$result += $NEW_LINE

# get free space before
$result += $NEW_LINE
$result += "Free Space Before Archive"
$result += GetFreeDriveSpaceInfo 30 $DrivesToCheck

## Adding 7zip to environment variables.
$7zippath = "$env:ProgramFiles\7-Zip\7z.exe"
Set-Alias 7zip $7zippath

## Replace x with the number of days before which the files have to be compressed.
#$LastWrite = (get-date).AddDays(-1470)
$LastWrite = (get-date).AddDays(-7)
$Date = (Get-Date).ToString("yyyy-MM-dd")

## Replace Path and Filter as per your need.
$Files = Get-ChildItem -Path "$SourcePath" -Filter "*.log" -Recurse -File | Where-Object {$_.LastWriteTime -le $LastWrite}

$Count = ($Files| Measure-Object).Count

$result += $NEW_LINE
$result += "No. of files to archive: " + $Count
$result += $NEW_LINE

$ArchiveFile = $ArchivePath + "IISLog_" + $Date + ".7z"

$FileIncludeList = $ArchivePath + "files_to_include.txt"
$OutputFile = $ArchivePath + "output.txt"

# delete existing include list file, if it exists
if (Test-Path $FileIncludeList) {
    Remove-Item -Path $FileIncludeList
}

ForEach ($File in $Files) {
    Add-Content -Path $FileIncludeList "$($File.fullname)"
}

# add to archive with full path, -sdel used to delete the source files that were included in the archive
7zip a -spf -sdel "$ArchiveFile" -i@"$FileIncludeList" | Out-File -FilePath "$OutputFile"
#7zip a -spf -sdel "$ArchiveFile" -i@"$FileIncludeList" > "$OutputFile"
#| Out-File -FilePath c:\temp\process.txt

# get free space after
$result += $NEW_LINE
$result += "Free Space After Archive"
$result += GetFreeDriveSpaceInfo 30 $DrivesToCheck

#Write-Output $result


# dir of destination
#$dir = Get-ChildItem -Path "$ArchivePath"

#Write-Output $dir

$dir = ""

$Files = Get-ChildItem -Path "$ArchivePath"

ForEach ($File in $Files)
{
    $dir = $dir + $NEW_LINE + $File.LastWriteTime.ToString("dd-MM-yyyy") + " - " + $File.Name + " (" + [math]::Round($File.length / 1MB, 1) + " MB)" 
}

#Write-Output $dir

$result += $dir

$result += $NEW_LINE
$result += $NEW_LINE
$result += "Finished " + (Get-Date).ToString("dd-MM-yyyy HH:mm:ss")

SendEmail "IIS Log Archive" $result 0