Link to home
Start Free TrialLog in
Avatar of michalek19
michalek19Flag for United States of America

asked on

Modify existing powershell to delete Bak files x number of days from csv log report with function to send report.

Modify existing Powershell to delete Bak files  X number of days based on generated content  (csv log) report with function to send report after removal.

I need Powershell script to ready csv log "fullname" column and remove any bak files folder older then 5 days from remote servers (computername column).
Below i included script to generate that csv log report.  Perhaps this script can be modified to do what i need in the above description.

This is csv log report

#TYPE System.Management.Automation.PSCustomObject                        
ComputerName           Name          FullName                                Size              Created
RTDB101                  Brie.bak         \\RTDB101\E$\Brie.bak      939.40 MB      9/23/2019 15:16
RTDB101                  SFWT.bak        \\RTDB101\E$\SFWT.bak      2,729.45 MB      9/23/2019 15:16
CDB102                         RES.bak        \\CDB102\E$\RES.bak      4,343.22 MB      8/12/2018
CDB102                        DEW.bak      \\CDB102\E$\DEW.bak      1,245.87 MB      10/10/2019
RDER103             WERT.bak      \\RDER103\E$\WERT.bak      1,235.87 MB      5/23/2019 0:00
RDER103            WERTY.BAK      \\RDER103\E$\WERTY.BAK      935.40 MB      5/23/2019 0:00


This is the script to generate this report.

$ComputersPath = "C:\Audit\computers.txt"
$LogPath = "C:\Audit\"
$LogFile = Join-Path -Path $LogPath -ChildPath BakFileReport.csv
$sendMailMessageParams = @{
      Smtpserver = "xxxxx.xxxx.xxx.xxx.net"
      From =       "BackupFileChecks_noreplay@xxxx.com"
      To =         "xxxx.xxxxn@xxxx.com"
      CC =         "yyal.yyyyan@yyyyys.com"
      Subject =    "Database Backup File Report"
      Body =        " Message."

      Attachments = $LogFile
}

Get-Content $ComputersPath | Where-Object {$_} | ForEach-Object {
      $Computer = $_
      Write-Host "Processing $($Computer) ..."
      ForEach ($Drive in "E", "F", "G", "I") {
            Write-Host "    - Drive $($Drive)" -NoNewline
            $count = 0
            If (Test-Path "\\$Computer\$($Drive)`$\" -ErrorAction Stop) {
                  Get-ChildItem "\\$Computer\$($Drive)`$\" -Filter *.bak -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
                        $count++
                        New-Object PSObject -Property ([ordered]@{
                              ComputerName = $Computer
                              Name = $_.Name
                              FullName = $_.FullName
                              Size = "{0:N2} MB" -f ($_.Length / 1mb)
                              CreationTime = $_.CreationTime
                        })
                  }
                  Write-Host " - $($count) files found." -ForegroundColor Green
            } Else {
                  Write-Host " - not accessible!" -ForegroundColor Yellow
            }
      }
} | Export-Csv $LogFile

Send-MailMessage @sendMailMessageParams
Avatar of oBdA
oBdA

Note: when you post code, please enclose it in [code] tags (see the toolbar above the Edit field).
Now, do you really want to report/delete based on the creation date? The creation date is the date the file itself was created, which can be actually newer than LastWriteTime, for example if you copy an old file - it will have today's creation date, but still the original older LastWriteTime.
The other way around, a file can have a creation date from way back in the past, but today's LastWriteTime, if it's constantly being updated.
Anyway, this will now delete old files based on CreationDate.
It is currently still in test mode and will only report the files it would normally delete to the console (in the csv, it will still report them as deleted).
To run it for real, remove the -WHATIF at the end of line 28.
To only generate the report as before, change line 15 as described in the comment.
$ComputersPath = "C:\Audit\computers.txt"
$LogPath = "C:\Audit\"
$LogFile = Join-Path -Path $LogPath -ChildPath BakFileReport.csv
$sendMailMessageParams = @{
	Smtpserver = "xxxxx.xxxx.xxx.xxx.net"
	From =       "BackupFileChecks_noreplay@xxxx.com"
	To =         "xxxx.xxxxn@xxxx.com"
	CC =         "yyal.yyyyan@yyyyys.com"
	Subject =    "Database Backup File Report"
	Body =        " Message."

	Attachments = $LogFile
}
## Set to [DateTime]::MinValue to not delete any files:
$deleteDate = (Get-Date).AddDays(-5)

Get-Content $ComputersPath | Where-Object {$_} | ForEach-Object {
	$Computer = $_
	Write-Host "Processing $($Computer) ..."
	ForEach ($Drive in "E", "F", "G", "I") {
		Write-Host "    - Drive $($Drive)" -NoNewline
		$count = 0
		If (Test-Path "\\$Computer\$($Drive)`$\" -ErrorAction Stop) {
			Get-ChildItem "\\$Computer\$($Drive)`$\" -Filter *.bak -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
				$count++
				If ($_.CreationTime -lt $deleteDate) {
					Try {
						Remove-Item -LiteralPath $_.FullName -Force -Confirm:$false -ErrorAction Stop -WHATIF
						$deleted = $true
					} Catch {
						$deleted = "ERROR: $($_.Exception.Message)"
					}
				} Else {
					$deleted = $false
				}
				New-Object PSObject -Property ([ordered]@{
					ComputerName = $Computer
					Name = $_.Name
					FullName = $_.FullName
					Size = "{0:N2} MB" -f ($_.Length / 1mb)
					CreationTime = $_.CreationTime
					Deleted = $deleted
				})
			}
		   Write-Host " - $($count) files found." -ForegroundColor Green
		} Else {
			Write-Host " - not accessible!" -ForegroundColor Yellow
		}
	}
} | Export-Csv -NoTypeInformation -Path $LogFile

Send-MailMessage @sendMailMessageParams

Open in new window

[oBdA] is spot-on, but it's worth pointing out his script will delete files before you add them to your list.  This may or may not be what you want.  To delete the files after they've been added to the list is a very small change.
Avatar of michalek19

ASKER

This is good.

What about if i want to delete old file based on Date Modified ? what do i need to change in the script.
Paul, To delete the files after they've been added to the list is a very small change. What would be change in the script?
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you both for your help. This was extremely helpful.