├── LICENSE ├── README.md └── Log-Manager.ps1 /LICENSE: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2024 Mike Galvin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Log Manager Utility 2 | 3 | Flexible clean up and backup of log files. 4 | 5 | For full change log and more information, [visit my site.](https://gal.vin/utils/log-manager-utility/) 6 | 7 | Log Manager Utility is available from: 8 | 9 | * [GitHub](https://github.com/Digressive/Log-Manager) 10 | * [The Microsoft PowerShell Gallery](https://www.powershellgallery.com/packages/Log-Manager) 11 | 12 | Please consider supporting my work: 13 | 14 | * Support with [Github Sponsors](https://github.com/sponsors/Digressive). 15 | * Support with a one-time donation using [PayPal](https://www.paypal.me/digressive). 16 | 17 | Please report any problems via the ‘issues’ tab on GitHub. 18 | 19 | -Mike 20 | 21 | ## Features and Requirements 22 | 23 | * The utility will delete files and folders older than X days. 24 | * It can also backup files and folders older than X days to another location. 25 | * It can also compress backups as a zip file. 26 | * The utility requires at least PowerShell 5.0 27 | * This utility has been tested on Windows 11, Windows 10, Windows Server 2022, Windows Server 2019, Windows Server 2016 and Windows Server 2012 R2. 28 | 29 | ## Generating A Password File For SMTP Authentication 30 | 31 | The password used for SMTP server authentication must be in an encrypted text file. To generate the password file, run the following command in PowerShell on the computer and logged in with the user that will be running the utility. When you run the command, you will be prompted for a username and password. Enter the username and password you want to use to authenticate to your SMTP server. 32 | 33 | Please note: This is only required if you need to authenticate to the SMTP server when send the log via e-mail. 34 | 35 | ``` powershell 36 | $creds = Get-Credential 37 | $creds.Password | ConvertFrom-SecureString | Set-Content c:\scripts\ps-script-pwd.txt 38 | ``` 39 | 40 | After running the commands, you will have a text file containing the encrypted password. When configuring the -Pwd switch enter the path and file name of this file. 41 | 42 | ## Configuration 43 | 44 | Here’s a list of all the command line switches and example configurations. 45 | 46 | | Command Line Switch | Description | Example | 47 | | ------------------- | ----------- | ------- | 48 | | -LogsPath | The path that contains the logs that the utility should process. | [path\] | 49 | | -LogKeep | Use this option to specify how long to keep logs for. Logs older than the number of days specified will be deleted. | [number] | 50 | | -BackupTo | The path the logs should be backed up to. A folder will be created inside this location. If this option is not used, backup will not be performed. | [path\] | 51 | | -BacKeep | Use this option to specify how long to keep the backups. Backups older than the number of days specified will be deleted. | [number] | 52 | | -Wd | Specify a 'working directory' for the creation of the zip file. | [path\] | 53 | | -Compress | This option will create a zip file of the log files. | N/A | 54 | | -Sz | Configure the utility to use 7-Zip to compress the backups. 7-Zip must be installed in the default location ```$env:ProgramFiles``` if it is not found, Windows compression will be used. | N/A | 55 | | -ZipName | Use this to name the zip file as you wish - the time and date will be appended to this name. | "'IIS Logs'" | 56 | | -L | The path to output the log file to. | [path\] | 57 | | -LogRotate | Remove logs produced by the utility older than X days | [number] | 58 | | -NoBanner | Use this option to hide the ASCII art title in the console. | N/A | 59 | | -Help | Display usage information. No arguments also displays help. | N/A | 60 | | -Subject | Specify a subject line. If you leave this blank the default subject will be used | "'[Server: Notification]'" | 61 | | -SendTo | The e-mail address the log should be sent to. For multiple address, separate with a comma. | [example@contoso.com] | 62 | | -From | The e-mail address the log should be sent from. | [example@contoso.com] | 63 | | -Smtp | The DNS name or IP address of the SMTP server. | [smtp server address] | 64 | | -Port | The Port that should be used for the SMTP server. If none is specified then the default of 25 will be used. | [port number] | 65 | | -User | The user account to authenticate to the SMTP server. | [example@contoso.com] | 66 | | -Pwd | The txt file containing the encrypted password for SMTP authentication. | [path\ps-script-pwd.txt] | 67 | | -UseSsl | Configures the utility to connect to the SMTP server using SSL. | N/A | 68 | 69 | ## Example 70 | 71 | ``` txt 72 | [path\]Log-Manager.ps1 -LogsPath [path\] -LogKeep [number] -BackupTo [path\] 73 | ``` 74 | 75 | This will backup and remove logs in the path specified older than X days. 76 | -------------------------------------------------------------------------------- /Log-Manager.ps1: -------------------------------------------------------------------------------- 1 | <#PSScriptInfo 2 | 3 | .VERSION 22.06.01 4 | 5 | .GUID 109eb5a2-1dd4-4def-9b9e-1d7413c8697f 6 | 7 | .AUTHOR Mike Galvin Contact: digressive@outlook.com 8 | 9 | .COMPANYNAME Mike Galvin 10 | 11 | .COPYRIGHT (C) Mike Galvin. All rights reserved. 12 | 13 | .TAGS Log Manager Clean up Backup Zip History MDT Microsoft Deployment Toolkit IIS Internet Information Services 14 | 15 | .LICENSEURI https://github.com/Digressive/Log-Manager?tab=MIT-1-ov-file 16 | 17 | .PROJECTURI https://gal.vin/utils/log-manager-utility/ 18 | 19 | .ICONURI 20 | 21 | .EXTERNALMODULEDEPENDENCIES 22 | 23 | .REQUIREDSCRIPTS 24 | 25 | .EXTERNALSCRIPTDEPENDENCIES 26 | 27 | .RELEASENOTES 28 | 29 | #> 30 | 31 | <# 32 | .SYNOPSIS 33 | Log Manager Utility - Flexible clean up and backup of log files. 34 | 35 | .DESCRIPTION 36 | Delete files and folders older than X days, or backup files and folders older than X days to another location and then remove files. 37 | Run with -help or no arguments for usage. 38 | #> 39 | 40 | ## Set up command line switches. 41 | [CmdletBinding()] 42 | Param( 43 | [alias("LogsPath")] 44 | $SourceUsr, 45 | [alias("LogKeep")] 46 | $LogHistory, 47 | [alias("BackupTo")] 48 | $BackupUsr, 49 | [alias("BacKeep")] 50 | $BacHistory, 51 | [alias("Wd")] 52 | $WorkDirUsr, 53 | [alias("ZipName")] 54 | $ZName, 55 | [alias("L")] 56 | $LogPathUsr, 57 | [alias("LogRotate")] 58 | $LogManOwnHistory, 59 | [alias("Subject")] 60 | $MailSubject, 61 | [alias("SendTo")] 62 | $MailTo, 63 | [alias("From")] 64 | $MailFrom, 65 | [alias("Smtp")] 66 | $SmtpServer, 67 | [alias("Port")] 68 | $SmtpPort, 69 | [alias("User")] 70 | $SmtpUser, 71 | [alias("Pwd")] 72 | [ValidateScript({Test-Path -Path $_ -PathType Leaf})] 73 | $SmtpPwd, 74 | [switch]$UseSsl, 75 | [switch]$Compress, 76 | [switch]$Sz, 77 | [switch]$Help, 78 | [switch]$NoBanner) 79 | 80 | If ($NoBanner -eq $False) 81 | { 82 | Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " 83 | __ _____ ___ __ __ __ _ _ __ ___ ____ ____ 84 | ( ) ( _ )/ __) ( \/ ) /__\ ( \( ) /__\ / __)( ___)( _ \ 85 | )(__ )(_)(( (_-. ) ( /(__)\ ) ( /(__)\( (_-. )__) ) / 86 | (____)(_____)\___/ (_/\/\_)(__)(__)(_)\_)(__)(__)\___/(____)(_)\_) 87 | __ __ ____ ____ __ ____ ____ _ _ 88 | ( )( )(_ _)(_ _)( ) (_ _)(_ _)( \/ ) Mike Galvin 89 | )(__)( )( _)(_ )(__ _)(_ )( \ / https://gal.vin 90 | (______) (__) (____)(____)(____) (__) (__) 91 | Version 22.06.01 92 | See -help for usage 93 | 94 | Donate: https://www.paypal.me/digressive 95 | " 96 | } 97 | 98 | If ($PSBoundParameters.Values.Count -eq 0 -or $Help) 99 | { 100 | Write-Host -Object "PLEASE NOTE! This tool can be destructive! Please test it on non critical files first! 101 | Usage: 102 | From a terminal run: [path\]Log-Manager.ps1 -LogsPath [path\] -LogKeep [number] -BackupTo [path\] 103 | This will backup and remove logs in the path specified older than X days. 104 | 105 | Use -BacKeep [number] option to specify how long to keep the backups. 106 | Use -Compress to create a zip file of the logs that are being backed up. 107 | Use -Sz to use 7-Zip to create a zip instead of Windows compression. 108 | 7-Zip must be installed in the default location, if it is not found, Windows compression will be used. 109 | 110 | Use -Wd [path\] to specify a 'working directory' for the creation of the zip file. 111 | Use -ZipName [name] to name the zip file as you wish - the time and date will be appended to this name. 112 | If this left blank a default name of logs-HOSTNAME-date-time.zip will be used. 113 | 114 | To output a log: -L [path\]. 115 | To remove logs produced by the utility older than X days: -LogRotate [number]. 116 | Run with no ASCII banner: -NoBanner 117 | 118 | To use the 'email log' function: 119 | Specify the subject line with -Subject ""'[subject line]'"" If you leave this blank a default subject will be used 120 | Make sure to encapsulate it with double & single quotes as per the example for Powershell to read it correctly. 121 | 122 | Specify the 'to' address with -SendTo [example@contoso.com] 123 | For multiple address, separate with a comma. 124 | 125 | Specify the 'from' address with -From [example@contoso.com] 126 | Specify the SMTP server with -Smtp [smtp server name] 127 | 128 | Specify the port to use with the SMTP server with -Port [port number]. 129 | If none is specified then the default of 25 will be used. 130 | 131 | Specify the user to access SMTP with -User [example@contoso.com] 132 | Specify the password file to use with -Pwd [path\]ps-script-pwd.txt. 133 | Use SSL for SMTP server connection with -UseSsl. 134 | 135 | To generate an encrypted password file run the following commands 136 | on the computer and the user that will run the script: 137 | " 138 | Write-Host -Object ' $creds = Get-Credential 139 | $creds.Password | ConvertFrom-SecureString | Set-Content [path\]ps-script-pwd.txt' 140 | } 141 | 142 | else { 143 | ## If logging is configured, start logging. 144 | ## If the log file already exists, clear it. 145 | If ($LogPathUsr) 146 | { 147 | ## Clean User entered string 148 | $LogPath = $LogPathUsr.trimend('\') 149 | 150 | ## Make sure the log directory exists. 151 | If ((Test-Path -Path $LogPath) -eq $False) 152 | { 153 | New-Item $LogPath -ItemType Directory -Force | Out-Null 154 | } 155 | 156 | $LogFile = ("Log-Man_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date)) 157 | $Log = "$LogPath\$LogFile" 158 | 159 | If (Test-Path -Path $Log) 160 | { 161 | Clear-Content -Path $Log 162 | } 163 | } 164 | 165 | ## 166 | ## Start of functions. 167 | ## 168 | ## Function to get date in specific format. 169 | Function Get-DateFormat 170 | { 171 | Get-Date -Format "yyyy-MM-dd HH:mm:ss" 172 | } 173 | 174 | ## Function for logging. 175 | Function Write-Log($Type, $Evt) 176 | { 177 | If ($Type -eq "Info") 178 | { 179 | If ($LogPathUsr) 180 | { 181 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Evt" 182 | } 183 | 184 | Write-Host -Object "$(Get-DateFormat) [INFO] $Evt" 185 | } 186 | 187 | If ($Type -eq "Succ") 188 | { 189 | If ($LogPathUsr) 190 | { 191 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Evt" 192 | } 193 | 194 | Write-Host -ForegroundColor Green -Object "$(Get-DateFormat) [SUCCESS] $Evt" 195 | } 196 | 197 | If ($Type -eq "Err") 198 | { 199 | If ($LogPathUsr) 200 | { 201 | Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Evt" 202 | } 203 | 204 | Write-Host -ForegroundColor Red -BackgroundColor Black -Object "$(Get-DateFormat) [ERROR] $Evt" 205 | } 206 | 207 | If ($Type -eq "Conf") 208 | { 209 | If ($LogPathUsr) 210 | { 211 | Add-Content -Path $Log -Encoding ASCII -Value "$Evt" 212 | } 213 | 214 | Write-Host -ForegroundColor Cyan -Object "$Evt" 215 | } 216 | } 217 | 218 | ## Function for the options post backup. 219 | Function OptionsRun 220 | { 221 | ## If the -keep switch AND the -compress switch are NOT configured. 222 | If ($Null -eq $BacHistory -And $Compress -eq $False) 223 | { 224 | ## Remove all previous backup folders, including ones from previous versions of this script. 225 | try { 226 | Get-ChildItem -Path $WorkDir -Filter "$ZName-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force 227 | } 228 | catch { 229 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 230 | } 231 | 232 | ## If a working directory is configured by the user, remove all previous backup folders, including 233 | ## ones from previous versions of this script. 234 | If ($WorkDir -ne $Backup) 235 | { 236 | try { 237 | Get-ChildItem -Path $Backup -Filter "$ZName-*-*-***-*-*" -Directory | Remove-Item -Recurse -Force 238 | } 239 | catch { 240 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 241 | } 242 | } 243 | 244 | Write-Log -Type Info -Evt "Removing previous backup folders" 245 | } 246 | 247 | ## If the -keep option IS configured AND the -compress option is NOT configured. 248 | else { 249 | If ($Compress -eq $False) 250 | { 251 | ## Remove previous backup folders older than the configured number of days, including 252 | ## ones from previous versions of this script. 253 | try { 254 | Get-ChildItem -Path $WorkDir -Filter "$ZName-*-*-***-*-*" -Directory | Where-Object CreationTime -lt (Get-Date).AddDays(-$BacHistory) | Remove-Item -Recurse -Force 255 | } 256 | catch { 257 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 258 | } 259 | 260 | ## If a working directory is configured by the user, remove previous backup folders 261 | ## older than the configured number of days remove all previous backup folders, 262 | ## including ones from previous versions of this script. 263 | If ($WorkDir -ne $Backup) 264 | { 265 | try { 266 | Get-ChildItem -Path $Backup -Filter "$ZName-*-*-***-*-*" -Directory | Where-Object CreationTime -lt (Get-Date).AddDays(-$BacHistory) | Remove-Item -Recurse -Force 267 | } 268 | catch { 269 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 270 | } 271 | } 272 | 273 | Write-Log -Type Info -Evt "Removing backup folders older than: $BacHistory days" 274 | } 275 | } 276 | 277 | ## Check to see if the -compress switch IS configured AND if the -keep switch is NOT configured. 278 | If ($Compress) 279 | { 280 | If ($Null -eq $BacHistory) 281 | { 282 | ## Remove all previous compressed backups, including ones from previous versions of this script. 283 | try { 284 | Remove-Item "$WorkDir\$ZName-*-*-***-*-*.zip" -Force 285 | } 286 | catch { 287 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 288 | } 289 | 290 | ## If a working directory is configured by the user, remove all previous compressed backups, 291 | ## including ones from previous versions of this script. 292 | If ($WorkDir -ne $Backup) 293 | { 294 | try { 295 | Remove-Item "$Backup\$ZName-*-*-***-*-*.zip" -Force 296 | } 297 | catch { 298 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 299 | } 300 | } 301 | 302 | Write-Log -Type Info -Evt "Removing previous compressed backups" 303 | } 304 | 305 | ## If the -compress switch IS configured AND if the -keep switch IS configured. 306 | else { 307 | ## Remove previous compressed backups older than the configured number of days, including 308 | ## ones from previous versions of this script. 309 | try { 310 | Get-ChildItem -Path "$WorkDir\$ZName-*-*-***-*-*.zip" | Where-Object CreationTime -lt (Get-Date).AddDays(-$BacHistory) | Remove-Item -Force 311 | } 312 | catch { 313 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 314 | } 315 | 316 | ## If a working directory is configured by the user, remove previous compressed backups older 317 | ## than the configured number of days, including ones from previous versions of this script. 318 | If ($WorkDir -ne $Backup) 319 | { 320 | try { 321 | Get-ChildItem -Path "$Backup\$ZName-*-*-***-*-*.zip" | Where-Object CreationTime -lt (Get-Date).AddDays(-$BacHistory) | Remove-Item -Force 322 | } 323 | catch { 324 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 325 | } 326 | } 327 | 328 | Write-Log -Type Info -Evt "Removing compressed backups older than: $BacHistory days" 329 | } 330 | 331 | ## If the -compress switch and the -Sz switch IS configured, test for 7zip being installed. 332 | ## If it is, compress the backup folder, if it is not use Windows compression. 333 | If ($Sz -eq $True) 334 | { 335 | If (Test-Path -Path "$env:programfiles\7-Zip\7z.exe") 336 | { 337 | Write-Log -Type Info -Evt "Compressing using 7-Zip compression" 338 | 339 | try { 340 | & "$env:programfiles\7-Zip\7z.exe" -bso0 a -tzip ("$WorkDir\$ZName-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date)) "$WorkDir\$ZName\*" 341 | } 342 | catch { 343 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 344 | } 345 | } 346 | 347 | else { 348 | Write-Log -Type Info -Evt "Compressing using Windows compression" 349 | Add-Type -AssemblyName "system.io.compression.filesystem" 350 | try { 351 | [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$ZName", ("$WorkDir\$ZName-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date))) 352 | } 353 | catch { 354 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 355 | } 356 | } 357 | } 358 | 359 | ## If the -compress switch IS configured and the -Sz switch is NOT configured, compress 360 | ## the backup folder using Windows compression. 361 | else { 362 | Write-Log -Type Info -Evt "Compressing using Windows compression" 363 | Add-Type -AssemblyName "system.io.compression.filesystem" 364 | [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$ZName", ("$WorkDir\$ZName-{0:yyyy-MM-dd_HH-mm-ss}.zip" -f (Get-Date))) 365 | } 366 | 367 | ## Clean up 368 | try { 369 | Get-ChildItem -Path $WorkDir -Filter "$ZName" -Directory | Remove-Item -Recurse -Force 370 | } 371 | catch { 372 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 373 | } 374 | 375 | ## If a working directory has been configured by the user, move the compressed 376 | ## backup to the backup location and rename to include the date. 377 | If ($WorkDir -ne $Backup) 378 | { 379 | try { 380 | Get-ChildItem -Path $WorkDir -Filter "$ZName-*-*-*-*-*.zip" | Move-Item -Destination $Backup 381 | } 382 | catch { 383 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 384 | } 385 | } 386 | } 387 | 388 | ## If the -compress switch is NOT configured AND if the -keep switch is NOT configured, rename 389 | ## the backup folder to include the date. 390 | else { 391 | try { 392 | Get-ChildItem -Path $WorkDir -Filter $ZName -Directory | Rename-Item -NewName ("$WorkDir\$ZName-{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date)) 393 | } 394 | catch { 395 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 396 | } 397 | 398 | If ($WorkDir -ne $Backup) 399 | { 400 | try { 401 | Get-ChildItem -Path $WorkDir -Filter "$ZName-*-*-***-*-*" -Directory | Move-Item -Destination ("$Backup\$ZName-{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date)) 402 | } 403 | catch { 404 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 405 | } 406 | } 407 | } 408 | } 409 | ## 410 | ## End of functions. 411 | ## 412 | 413 | ## 414 | ## Start main process. 415 | ## 416 | 417 | If ($Null -eq $SourceUsr) 418 | { 419 | Write-Log -Type Err -Evt "You must specify -LogsPath." 420 | Exit 421 | } 422 | 423 | else { 424 | ## Clean User entered string 425 | $Source = $SourceUsr.trimend('\') 426 | 427 | If ($Null -eq $BackupUsr -And $BacHistory) 428 | { 429 | Write-Log -Type Err -Evt "You must specify -BackupTo to use -BacKeep." 430 | Exit 431 | } 432 | 433 | If ($Null -eq $BackupUsr -And $WorkDirUsr) 434 | { 435 | Write-Log -Type Err -Evt "You must specify -BackupTo to use -Wd." 436 | Exit 437 | } 438 | 439 | If ($Compress -eq $false -And $Null -ne $ZName) 440 | { 441 | Write-Log -Type Err -Evt "You must specify -Compress to use -ZipName." 442 | Exit 443 | } 444 | 445 | If ($Compress -eq $false -And $Sz -eq $true) 446 | { 447 | Write-Log -Type Err -Evt "You must specify -Compress to use -Sz." 448 | Exit 449 | } 450 | 451 | If ($Compress -eq $true -And $Null -eq $BackupUsr) 452 | { 453 | Write-Log -Type Err -Evt "You must specify -BackupTo to use -Compress." 454 | Exit 455 | } 456 | 457 | ## Clean User entered string 458 | If ($BackupUsr) 459 | { 460 | $Backup = $BackupUsr.trimend('\') 461 | } 462 | 463 | If ($WorkDirUsr) 464 | { 465 | $WorkDir = $WorkDirUsr.trimend('\') 466 | } 467 | 468 | If ($Null -eq $LogPathUsr -And $SmtpServer) 469 | { 470 | Write-Log -Type Err -Evt "You must specify -L [path\] to use the email log function." 471 | Exit 472 | } 473 | } 474 | 475 | ## getting Windows Version info 476 | $OSVMaj = [environment]::OSVersion.Version | Select-Object -expand major 477 | $OSVMin = [environment]::OSVersion.Version | Select-Object -expand minor 478 | $OSVBui = [environment]::OSVersion.Version | Select-Object -expand build 479 | $OSV = "$OSVMaj" + "." + "$OSVMin" + "." + "$OSVBui" 480 | 481 | ## 482 | ## Display the current config and log if configured. 483 | ## 484 | Write-Log -Type Conf -Evt "************ Running with the following config *************." 485 | Write-Log -Type Conf -Evt "Utility Version:.......22.06.01" 486 | Write-Log -Type Conf -Evt "Hostname:..............$Env:ComputerName." 487 | Write-Log -Type Conf -Evt "Windows Version:.......$OSV." 488 | 489 | If ($SourceUsr) 490 | { 491 | Write-Log -Type Conf -Evt "Path to process:.......$SourceUsr." 492 | } 493 | 494 | If ($Null -ne $LogHistory) 495 | { 496 | Write-Log -Type Conf -Evt "Logs to keep:..........$LogHistory days" 497 | } 498 | 499 | If ($BackupUsr) 500 | { 501 | Write-Log -Type Conf -Evt "Backup directory:......$BackupUsr." 502 | } 503 | 504 | If ($WorkDirUsr) 505 | { 506 | Write-Log -Type Conf -Evt "Working directory:.....$WorkDirUsr." 507 | } 508 | 509 | If ($Null -ne $BacHistory) 510 | { 511 | Write-Log -Type Conf -Evt "Backups to keep:.......$BacHistory days" 512 | } 513 | 514 | If ($ZName) 515 | { 516 | Write-Log -Type Conf -Evt "Zip file name:.........$ZName + date and time." 517 | } 518 | 519 | If ($Compress) 520 | { 521 | Write-Log -Type Conf -Evt "-Compress switch is:...$Compress." 522 | } 523 | 524 | If ($Sz) 525 | { 526 | Write-Log -Type Conf -Evt "-Sz switch is:.........$Sz." 527 | } 528 | 529 | If ($LogPathUsr) 530 | { 531 | Write-Log -Type Conf -Evt "Log directory:.........$LogPath." 532 | } 533 | 534 | If ($Null -ne $LogManOwnHistory) 535 | { 536 | Write-Log -Type Conf -Evt "Logs to keep:..........$LogManOwnHistory days." 537 | } 538 | 539 | If ($MailTo) 540 | { 541 | Write-Log -Type Conf -Evt "E-mail log to:.........$MailTo." 542 | } 543 | 544 | If ($MailFrom) 545 | { 546 | Write-Log -Type Conf -Evt "E-mail log from:.......$MailFrom." 547 | } 548 | 549 | If ($MailSubject) 550 | { 551 | Write-Log -Type Conf -Evt "E-mail subject:........$MailSubject." 552 | } 553 | 554 | If ($SmtpServer) 555 | { 556 | Write-Log -Type Conf -Evt "SMTP server:...........$SmtpServer." 557 | } 558 | 559 | If ($SmtpPort) 560 | { 561 | Write-Log -Type Conf -Evt "SMTP Port:.............$SmtpPort." 562 | } 563 | 564 | If ($SmtpUser) 565 | { 566 | Write-Log -Type Conf -Evt "SMTP user:.............$SmtpUser." 567 | } 568 | 569 | If ($SmtpPwd) 570 | { 571 | Write-Log -Type Conf -Evt "SMTP pwd file:.........$SmtpPwd." 572 | } 573 | 574 | If ($SmtpServer) 575 | { 576 | Write-Log -Type Conf -Evt "-UseSSL switch is:.....$UseSsl." 577 | } 578 | Write-Log -Type Conf -Evt "************************************************************" 579 | Write-Log -Type Info -Evt "Process started" 580 | ## 581 | ## Display current config ends here. 582 | ## 583 | 584 | ## Count the number of files that are old enough to work on in the configured directory 585 | ## If the number of the files to work on is not zero then proceed. 586 | $FileNo = Get-ChildItem -Path $Source -Recurse | Where-Object CreationTime -lt (Get-Date).AddDays(-$LogHistory) | Measure-Object 587 | 588 | If ($FileNo.count -ne 0) 589 | { 590 | ## If time -days switch isn't configured, then set it to 0 591 | If ($Null -eq $LogHistory) 592 | { 593 | $LogHistory = "0" 594 | } 595 | 596 | If ($Null -eq $BacHistory) 597 | { 598 | $BacHistory = "0" 599 | } 600 | 601 | ## If the user has not configured the working directory, set it as the backup directory if needed. 602 | If ($BackupUsr) 603 | { 604 | ## Make sure the directory exists. 605 | If ((Test-Path -Path $Backup) -eq $False) 606 | { 607 | New-Item $Backup -ItemType Directory -Force | Out-Null 608 | } 609 | 610 | If ($Null -eq $WorkDirUsr) 611 | { 612 | $WorkDir = "$Backup" 613 | } 614 | } 615 | 616 | ## If the user has not configured a zip name, set it as the default. 617 | If ($Null -eq $ZName) 618 | { 619 | $ZName = "Logs-$env:computername" 620 | } 621 | 622 | Write-Log -Type Info -Evt "The following objects will be processed:" 623 | Get-ChildItem -Path $Source | Select-Object -ExpandProperty Name 624 | 625 | If ($LogPathUsr) 626 | { 627 | Get-ChildItem -Path $Source | Select-Object -ExpandProperty Name | Out-File -Append $Log -Encoding ASCII 628 | } 629 | 630 | If ($BackupUsr) 631 | { 632 | ## Test for the existence of a previous backup. If it exists, delete it. 633 | If (Test-Path -Path "$WorkDir\$ZName") 634 | { 635 | try { 636 | Remove-Item "$WorkDir\$ZName" -Recurse -Force 637 | } 638 | catch { 639 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 640 | } 641 | } 642 | 643 | Write-Log -Type Info -Evt "Attempting to move objects older than: $LogHistory days" 644 | 645 | try { 646 | New-Item -Path "$WorkDir\$ZName" -ItemType Directory | Out-Null 647 | Get-ChildItem -Path $Source | Where-Object CreationTime -lt (Get-Date).AddDays(-$LogHistory) | Copy-Item -Destination "$WorkDir\$ZName" -Recurse -Force 648 | } 649 | catch { 650 | $_.Exception.Message | Write-Log -Type Err -Evt $_ 651 | } 652 | 653 | OptionsRun 654 | } 655 | 656 | ## If no backup options were configured, or after doing the previous operations, remove the old files. 657 | Get-ChildItem -Path $Source | Where-Object CreationTime -lt (Get-Date).AddDays(-$LogHistory) | Remove-Item -Recurse 658 | Write-Log -Type Info -Evt "Deleting logs older than: $LogHistory days" 659 | 660 | ## 661 | ## Main process ends here. 662 | ## 663 | } 664 | 665 | ## If there are no objects old enough to process then finish. 666 | else { 667 | Write-Log -Type Info -Evt "There are no objects to process." 668 | } 669 | 670 | Write-Log -Type Info -Evt "Process finished." 671 | 672 | If ($Null -ne $LogManOwnHistory) 673 | { 674 | ## Cleanup logs. 675 | Write-Log -Type Info -Evt "Deleting Log Manager logs older than: $LogManOwnHistory days" 676 | Get-ChildItem -Path "$LogPath\Log-Man_*" -File | Where-Object CreationTime -lt (Get-Date).AddDays(-$LogManOwnHistory) | Remove-Item -Recurse 677 | } 678 | 679 | ## This whole block is for e-mail, if it is configured. 680 | If ($SmtpServer) 681 | { 682 | If (Test-Path -Path $Log) 683 | { 684 | ## Default e-mail subject if none is configured. 685 | If ($Null -eq $MailSubject) 686 | { 687 | $MailSubject = "Log Manager Utility Log" 688 | } 689 | 690 | ## Default Smtp Port if none is configured. 691 | If ($Null -eq $SmtpPort) 692 | { 693 | $SmtpPort = "25" 694 | } 695 | 696 | ## Setting the contents of the log to be the e-mail body. 697 | $MailBody = Get-Content -Path $Log | Out-String 698 | 699 | ForEach ($MailAddress in $MailTo) 700 | { 701 | ## If an smtp password is configured, get the username and password together for authentication. 702 | ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL. 703 | If ($SmtpPwd) 704 | { 705 | $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString 706 | $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt) 707 | 708 | ## If -ssl switch is used, send the email with SSL. 709 | ## If it isn't then don't use SSL, but still authenticate with the credentials. 710 | If ($UseSsl) 711 | { 712 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $SmtpCreds 713 | } 714 | 715 | else { 716 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -Credential $SmtpCreds 717 | } 718 | } 719 | 720 | else { 721 | Send-MailMessage -To $MailAddress -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort 722 | } 723 | } 724 | } 725 | 726 | else { 727 | Write-Host -ForegroundColor Red -BackgroundColor Black -Object "There's no log file to email." 728 | } 729 | } 730 | ## End of Email block 731 | } 732 | ## End --------------------------------------------------------------------------------