Powershell, Scripts

Check and Delete .BLG Files in “C:\PerfLogs\Admin” folder that are older than 2 days

Last night I was approached to script a tool that can Check and Delete .BLG Files in “C:\PerfLogs\Admin” folder that are older than 2 days.

I choose #PowerShell for obvious reasons and here is something I put in real quick.. This script can be modified to suit your needs.

<#
Author: Murali Palla
email: [email protected]
#>
<#
.Synopsis
   Script to Check and Delete .BLG Files in "C:\PerfLogs\Admin" folder that are older than 2 days
.DESCRIPTION
   Intended to run in a Schedule Task and designed to run from Local Server
   Creates a Folder with Name "DeleteLogs" in the PerfLogs folder and stores Logs for each deleted file.
#>
    [CmdletBinding()]
    Param
    (
        [String]$FolderToDelete = "C:\PerfLogs\Admin",
        [String]$DeleteLog = "C:\PerfLogs\DeleteLogs",
        $LogFolder = "$DeleteLog\$(Get-Date -Format MMM-yyyy)",
        $LogFile= "$LogFolder\$(Get-Date -Format dd-MMM-yyyy)"+".csv",
        $CurrentDateTime = (Get-Date -Format "dd-MMM-yyyy hh:mm tt"),
        $Header= "Date,FileName,Modified Date,Status"
    )

    Begin
    {              
        if (!(Test-Path $DeleteLog -ErrorAction SilentlyContinue)) 
            {
                New-Item -ItemType directory -Path $DeleteLog | Out-Null
            }
        if (!(Test-Path $LogFolder -ErrorAction SilentlyContinue)) 
            {
                New-Item -ItemType directory -Path $LogFolder | Out-Null
            }
        if (!(Test-Path $LogFile  -ErrorAction SilentlyContinue)) 
            {
                $Header | Out-File -Append $LogFile -Encoding utf8
            }
        $Error.Clear()
        if (!(Test-Path -Path $FolderToDelete -ErrorAction SilentlyContinue))
            {
            "$CurrentDateTime,N/A,N/A,Admin Folder Missing" | Out-File "$LogFile" -Append 
            Exit
            }
        else{
            $FileList = Get-ChildItem $FolderToDelete | Where-Object {$PSItem.extension -eq ".Blg"}
            }

        foreach ($File in $FileList) 
        {
            $LastModified = New-TimeSpan -Start $File.LastWriteTime
            if ($LastModified.Days -gt "2") 
                {
                $Error.Clear()
                Remove-Item -Path $File.FullName -Force -ErrorAction SilentlyContinue
                if ($Error)
                    {
                        "$(Get-Date -Format dd-MMM-yyyy),$($File.Name),$($File.LastWriteTime),File Locked" | Out-File -FilePath $LogFile -Append
                        $error.Clear()
                    }
                else {"$(Get-Date -Format dd-MMM-yyyy),$($File.Name),$($File.LastWriteTime),Deleted" | Out-File -FilePath $LogFile -Append}
                }
        }
    }

 

Loading