BAK extension file audit and BAK extension files deletion after x number of days with function to send report

michalek19
michalek19 used Ask the Experts™
on
Hi

I need your help to put together Powershell script to

Script 1 - BAK extension file Audit

1. Script needs to be able to use input server file (server bulk)
2. Scan servers drives (E:\, F:\, G:\ or I:\) or be able to select drives
3. Look for  “*.bak” extension files.
4. Generate CSV output files with
       a. server name
       b. Bak file name and path
       c. File Size
       d. Dates temp of the file.
       3. hash
5. Email report to specific email address

I have a Audit script but it doesn't work correctly. It scans all drives, doesn't provide date of BAK file creation. It doesn't sent email with report

$ExtensionList = @('.bak')
Get-PSDrive -PSProvider FileSystem |
    ForEach-Object  {
        Get-ChildItem -Path $_.Root -Recurse -ErrorAction SilentlyContinue |
            Where-Object { $ExtensionList -eq $_.Extension } |
            ## ForEach-Object { $_.Name, $_.FullName, $_.GetHashCode() }
            Select-Object @{Name="Name";Expression={$_.Name}}, @{Name="Hash";Expression={$_.GetHashCode()}}, @{Name="FullName";Expression={$_.FullName}} |
            Export-Csv -Path C:\Temp\BAKAudit\BAKAuditReport.csv -NoTypeInformation -Append

I don't have BAK deletion script, which should do as follows

Script 2 - BAK Deletion
1. Use generated output file (from script 1) and remove"Bak" file older then 3 days.
2. Once the deletion is completed another report should be created showing what bak files from which server and from which path were removed providing their original date-stamp, server name and path with column status remove. This report (CSV) should be sent to specific email address.

Please help, M
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ste5anSenior Developer

Commented:
Sending e-mail requires that you have access to a SMTP server (see Send-MailMessage):

Script 1:
$AuditFile = 'C:\Temp\BAKAuditReport.csv'
$FilePattern = '*.bak'

Get-PSDrive -PSProvider FileSystem |
    ForEach-Object -Process {
        $Path = Join-Path -Path $_.Root -ChildPath $FilePattern        
        $Files = Get-ChildItem -Path $Path -Recurse -ErrorAction SilentlyContinue
        $Files |
            Select-Object @{ Name="Name"; Expression={$_.Name} }, @{ Name="Hash"; Expression={$_.GetHashCode()} }, @{ Name="FullName"; Expression={$_.FullName} }, @{ Name="CreationTime"; Expression={$_.CreationTime} } |
            Export-Csv -Append -NoTypeInformation -Path $AuditFile
    }

If (@($Files).Length -Gt 0) {
    Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>' -Subject 'Test mail' -Attachments $AuditFile
}

Open in new window


Script 2 is similar:
$AuditFile = 'C:\Temp\BAKAuditReport-Deletion.csv'
$Date = (Get-Date).Add(-3).Date
$FilePattern = '*.bak'

Get-PSDrive -PSProvider FileSystem |
    ForEach-Object -Process {
        $Path = Join-Path -Path $_.Root -ChildPath $FilePattern
        $Files = Get-ChildItem -Path $Path -Recurse -ErrorAction SilentlyContinue |
            Where-Object -Property CreationTime -Lt $Date
        $Files |
            Select-Object @{ Name="Name"; Expression={$_.Name} }, @{ Name="Hash"; Expression={$_.GetHashCode()} }, @{ Name="FullName"; Expression={$_.FullName} }, @{ Name="CreationTime"; Expression={$_.CreationTime} } |
            Export-Csv -Append -NoTypeInformation -Path $AuditFile
    }

If (@($Files).Length -Gt 0) {
    '*** Send Mail ***'
    '*** Delete $Files ***'
    $Files
}

Open in new window


p.s. depending on the kind of audit, you need to send an e-mail always. Cause otherwise the recipient cannot differ between no files found and something went wrong.

Author

Commented:
I would like to run this script against multiple servers as well as I need to be able to select which drive should be scan for “bak”. Would you be able to add this into script?

Author

Commented:
Multiple servers means remote servers
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

ste5anSenior Developer

Commented:
Nope, cause I don't can test remoting PS scripts.

Author

Commented:
I can test it.

Can you add to this script Invoke-Command -ComputerName “  from the file”  With option to select drive ?
Top Expert 2016

Commented:
$ExtensionList = @('.bak')
$baddrives = @()
$totalbakfiles = @()
$Drives = Get-PSDrive -PSProvider FileSystem 
$totalDrives = $Drives.Count
    for($i = 1; $i -le $totalDrives; $i++)
    {
      $drive = $drives[$i-1]
      Write-Progress -Activity "Looking for BAK Files" -Status "Drive: $drive" -PercentComplete ($i /$totalDrives*100)
      $filelist = @{}
      write-output ("Checking Drive: {0}" -f $drive)
      $files = Get-ChildItem -Path $drives[$i-1].Root -Recurse -ErrorAction SilentlyContinue -Include "*.bak"
      foreach($file in $files) {
        write-output $file.fullname
        $fillist2 = @{
          Name=$file.name
          Hash = $file.gethashcode()
          Fullname = $file.fullname
          ModifiedDate = $file.LastWriteTime
          }
                   
                   $fillist2
                       $totalbakfiles += $fillist2
                   
                   }
            }
            $outfile = "Bak FILES Report: "+ (get-date -Format "yyyy-MM-dd").ToString() + "csv"
             -
            $totalbakfiles | Export-Csv '\\ryzen\c$\temp\' + $outfile -nti -Append
            
            
            

Open in new window

Author

Commented:
This is very close what i am looking for except. I don;t want to scan C:\ drive.  The script should scan all of the drive (and their directories and directories) except A, C and D.

Once the scan is completed is should be able to sent an email with the report to specific email address.

Author

Commented:
Also, it is missing bak file size

Author

Commented:
There is one more thing. How to run this script against list of servers (servers.txt)

Author

Commented:
I made a change under $Drives = Get-PSDrive E, F, G . I was able to select which drives i want to scan but the report can't be generated.

Here is the error message. Can you please help?

Cannot convert value "Bak FILES Report: 2019-09-25csv" to type "System.Int32". Error: "Input string was not in a
correct format."
At C:\Users\rejmanm\Desktop\BAKAudit\BAKAUDITFILES\new\Test2.ps1:28 char:13
+             $outfile = "Bak FILES Report: "+ (get-date -Format "yyyy- ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger


Made change to $Drives and added  Size=$file.length

$ExtensionList = @('.bak')
$baddrives = @()
$totalbakfiles = @()
$Drives = Get-PSDrive [b]E, F, G [/b]
$totalDrives = $Drives.Count
    for($i = 1; $i -le $totalDrives; $i++)
    {
      $drive = $drives[$i-1]
      Write-Progress -Activity "Looking for BAK Files" -Status "Drive: $drive" -PercentComplete ($i /$totalDrives*100)
      $filelist = @{}
      write-output ("Checking Drive: {0}" -f $drive)
      $files = Get-ChildItem -Path $drives[$i-1].Root -Recurse -ErrorAction SilentlyContinue -Include "*.bak"
      foreach($file in $files) {
        write-output $file.fullname
        $fillist2 = @{
          Name=$file.name
          Hash = $file.gethashcode()
          Fullname = $file.fullname
          ModifiedDate = $file.LastWriteTime
		  Size=$file.length
          }
                   
                   $fillist2
                       $totalbakfiles += $fillist2
                   
                   }
            }
            $outfile = "Bak FILES Report: "+ (get-date -Format "yyyy-MM-dd").ToString() + "csv" - $totalbakfiles | Export-Csv 'C:\temp1\New\' + $outfile -nti -Append

Open in new window

i found my solution

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial