Wednesday, February 1, 2012

[Powershell] Delete .log file older than 1 month in a specified folder

Here is a short script that will help you to clean a folder that contains .log files that have a creation date older than one month. The function can use an argument to be verbose or not - Verbose mode write events in the Operations Manager Event Log when it's launched by SCOM.

Save this few line in a DeleteOldLogs.ps1 file.
  1. param ($FolderPath, $Debug)
  2. if ($debug -ne "true"){$debug = [bool]$false}else{$debug = [bool]$true}
  3. $Script:API             = new-object -comObject "MOM.ScriptAPI"
  4. $Script:Bag             = $Script:API.CreatePropertyBag()
  5. $Script:LOG_ERROR       = 1
  6. $Script:LOG_WARNING     = 2
  7. $Script:LOG_INFORMATION = 4
  8. $Script:ScriptName      = "DeleteOldLogs.ps1"
  9. $Script:Arguments       = "Received Arguments:`FolderPath = $FolderPath `rDebug = $debug"
  10. function Write-DebugInfo([string] $msg)
  11. {
  12.     if ($debug)
  13.     {
  14.         $Script:API.LogScriptEvent("$ScriptName",100,$Script:LOG_INFORMATION,"`r$Arguments`r`r$msg")
  15.     }
  16. }
  17. function Write-ErrorInfo([string] $msg)
  18. {
  19.     $Script:API.LogScriptEvent("$ScriptName",500,$Script:LOG_ERROR,"`r$Arguments`r`r$msg")
  20. }
  21. $date= (get-date).AddMonths(-1)
  22. $Files = get-childitem -Path $FolderPath -include *.log -recurse | Where-Object {$_.CreationTime -lt $date}
  23. foreach ($File in $Files)
  24. {
  25.  if ($File) {
  26.  Write-DebugInfo "Deleting File '$File'"
  27.  Remove-Item $File | out-null
  28. }
  29. }

 In the powershell command shell, just launch
> DeleteOldLogs.PS1 "C:\temp" "true"

This posting is provided "AS IS" with no warranties.

No comments:

Post a Comment