8
0
Skriptentwickung/archive/Modules/Archiv/Remove-Item-withLogging.psm1
2024-11-08 15:39:19 +01:00

117 lines
3.3 KiB
PowerShell

Function Remove-Item-withLogging {
<#
.SYNOPSIS
Function will delete Items selected by Path, Name and Age.
.DESCRIPTION
Function will delete Items selected by Path, Name and Age, with logging this.
For a successful performed deletion, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Variables
Path, FileKeepTime, FileBaseName, Item, Items
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
Number: 1.1.0.0 / Date: 21.11.2016
.PARAMETER Path
Give the Full Path, where the Item(s) located, which should be deleted.
.PARAMETER FileKeepTime
Give the time in Days, which Items should be deleted, which are older than...
.PARAMETER FileBaseName
Give the <Filename> an which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.
.EXAMPLE
Remove-Item-withLogging -Path "E:\LogFiles" -FileKeepTime 5 -FileBaseName Filename
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the Full Path, where the Item(s) located, which should be deleted.')]
[ValidateNotNullOrEmpty()]
[String]$Path=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the time in Days, which Item(s) should be deleted, which are older than...')]
[ValidateRange(0,1000)]
[Int]$FileKeepTime=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the Filename an which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.')]
[ValidateNotNullOrEmpty()]
[String]$FileBaseName=$NULL
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ($FileKeepTime -gt 0) {
Write-Logfile -LogLine "Files should be removed which are older than $FileKeepTime Day(s)."
$Items = (Get-ChildItem -Path "$Path\*" -Filter *.log | where {$_.Name -like "*$FileBaseName*" -and $_.lastwritetime -lt $((Get-Date).AddDays(-$FileKeepTime)) -and -not $_.psiscontainer})
IF ($Items -eq $null) {
Write-Logfile -LogLine "Found no old Files."
Return $False
} #end if
ELSE {
Write-Logfile -LogLine "Deleting old Files (Found: $($Items.count)) :"
FOREACH ($Item in $Items) {
Try {
Remove-Item -Path $Item -Force -Verbose -ErrorVariable Error -ErrorAction Continue
Write-Logfile -LogLine "LogFile: $Item was removed."
Return $True
} #end try
Catch {
Write-Logfile -LogLine "File: $Item cannot been removed."
Write-Logfile -LogLine "Please check your privileges!"
} #end catch
} #end foreach
} #end else
} #end if
ELSE {
Write-Logfile -LogLine "You disabled File deleting, they all will be kept."
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function