Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

a PowerShell script that automates file and folder operations, specifically targeting the task of archiving or cleaning up old log files #13

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Certainly! Below is a PowerShell script that automates file and folder operations, specifically targeting the task of archiving or cleaning up old log files. This script identifies log files older than a specified threshold, archives them to a designated folder, and then optionally deletes the original log files.

# Specify the log directory and archive directory
$LogDirectory = "C:\Path\To\LogFiles"
$ArchiveDirectory = "C:\Path\To\Archive"

# Specify the threshold for log file age in days
$ThresholdDays = 30

# Create the archive directory if it doesn't exist
if (-not (Test-Path -Path $ArchiveDirectory)) {
    New-Item -ItemType Directory -Path $ArchiveDirectory
}

# Get log files older than the threshold
$OldLogFiles = Get-ChildItem -Path $LogDirectory -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$ThresholdDays) }

# Archive old log files
foreach ($LogFile in $OldLogFiles) {
    $ArchivePath = Join-Path -Path $ArchiveDirectory -ChildPath $LogFile.Name
    Move-Item -Path $LogFile.FullName -Destination $ArchivePath -Force
    Write-Host "Archived $($LogFile.Name) to $($ArchivePath)"
}

# Optional: Delete original log files after archiving
# Uncomment the lines below if you want to delete the original log files

# foreach ($LogFile in $OldLogFiles) {
#     Remove-Item -Path $LogFile.FullName -Force
#     Write-Host "Deleted $($LogFile.Name)"
# }

Explanation:

  1. Modify the $LogDirectory and $ArchiveDirectory variables with the paths to your log files and the desired archive folder.

  2. Set the $ThresholdDays variable to the number of days beyond which log files should be considered old.

  3. The script identifies log files older than the threshold using Get-ChildItem and filters based on the LastWriteTime.

  4. It creates the archive directory if it doesn't already exist.

  5. The script then archives the old log files to the specified archive directory using Move-Item.

  6. Optionally, you can uncomment the lines that use Remove-Item to delete the original log files after archiving.

  7. Customize the script based on your specific needs and run it periodically, for example, using Task Scheduler, to automate the process of archiving or cleaning up old log files.