Skip to content

Instantly share code, notes, and snippets.

@TheRockStarDBA
Created September 6, 2019 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheRockStarDBA/36fbac1eaec40b25584362824fcc91e4 to your computer and use it in GitHub Desktop.
Save TheRockStarDBA/36fbac1eaec40b25584362824fcc91e4 to your computer and use it in GitHub Desktop.
Function to delete old backup files from NAS
Function global:Clean-NASOldFiles {
<#
.SYNOPSIS
Deletes the files on NAS folder that are older than MinAge .. default is 9.
Make sure you do necessary changes for CHANGE HERE !
.Author
Kin Shah https://dba.stackexchange.com/users/8783/kin-shah
.DESCRIPTION
Lists all files under a specified folder regardless of character limitation on path depth.
.PARAMETER Path
The NAS Path
.PARAMETER Filter
Optional parameter to specify a specific file or file type. Wildcards (*) allowed.
Default is '*.bak','*.trn','*.inc'
.PARAMETER MaxAge
Exclude files older than n days.
.PARAMETER MinAge
Exclude files newer than n days. Default is 9 Days
. PARAMETER Confirm
Confirm for deletion. Default is N - for saftey ! This way you dont accidentally delete files !!
.EXAMPLE
Clean-NASOldFiles -Path "\\sharedLocation\sqlserver_backups" -MinAge 9 -confirm "N" # this will just print out waht files will be deleted
Clean-NASOldFiles -Path "\\sharedLocation\sqlserver_backups" -MinAge 9 -confirm "Y" # this will actually delete the files older than 9 days !!
#>
[cmdletbinding(DefaultParameterSetName='Filter')]
Param (
[parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('FullName')]
[string[]]$Path = $PWD,
[parameter(ParameterSetName='Filter')]
[string[]]$Filter = ('*.bak','*.trn','*.inc'),
[parameter()]
[int]$MinAge = 9,
[ValidateSet('Y','N')]
[string[]] $confirm = "N"
)
Begin {
$params = New-Object System.Collections.Arraylist
$params.AddRange(@("/L","/S","/NJH","/BYTES","/FP","/NC","/NDL","/TS","/XJ","/R:0","/W:0"))
If ($PSBoundParameters['MinAge']) {
$params.Add("/MinAge:$MinAge") | Out-Null
}
}
Process {
if (test-path $Path) {
[string] $global:LogDir = "D:\MSSQL\Logs\" # CHANGE HERE ! this is the log file to keep track of what files will be deleted !
$Path_Log = (($Path -replace "\\", "") -replace ":", "").Trim() + ".log"
$today = (Get-Date).DayOfWeek
$hour = (get-date).Hour
if (!(Test-Path "$global:LogDir$Path_Log"))
{
New-Item -path $global:LogDir -name $Path_Log -type "file"
write-output "$global:LogDir$Path_Log - File created "
}
else
{
write-output "$global:LogDir$Path_Log - File already exists"
}
ForEach ($item in $Path) {
Try {
$item = (Resolve-Path -LiteralPath $item -ErrorAction Stop).ProviderPath
If (-Not (Test-Path -LiteralPath $item -Type Container -ErrorAction Stop)) {
Write-Warning ("{0} is not a directory and will be skipped" -f $item)
Return
}
Write-Verbose ("Scanning {0}" -f $item)
Invoke-Expression $Script | ForEach-object {
Try {
If ($_.Trim() -match "^(?<Size>\d+)\s(?<Date>\S+\s\S+)\s+(?<FullName>.*)") {
$object = New-Object PSObject -Property @{
FullName = $matches.FullName
LastWriteTime = [datetime]$matches.Date
SizeinMB = [math]::round($matches.Size / 1MB, 2)
}
$object.pstypenames.insert(0,'System.IO.RobocopyDirectoryInfo')
# Run the script if it confirm = Y
if (($confirm -match "Y") ) {
$object.fullname | Remove-Item -Force
WriteLog -Msg $object.fullname -Log $global:LogDir$Path_Log
}
else {
Write-Output "Files are not deleted since Confrim was $confirm"
write-output $object
}
} Else {
Write-Verbose ("Not matched: {0}" -f $_)
}
} Catch {
Write-Warning ("{0}" -f $_.Exception.Message)
Return
}
}
} Catch {
Write-Warning ("{0}" -f $_.Exception.Message)
Return
}
} # End of foreach $item
}
else {
#false -- exit reporting failure ...
write-output "the folder $Path does not exist! Please check !!"
}
} # End of process
} # End of function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment