Public/Get-LogFilesByPatternAndRetention.ps1

Function Get-LogFilesByPatternAndRetention {
    <#
    .SYNOPSIS
        Retrieves and lists log files based on a specified name pattern and retention policy.
 
    .DESCRIPTION
        The `Get-LogFilesByPatternAndRetention` function searches for log files in a specified directory that match a given name pattern. It sorts the log files by their last write time in descending order and retains a specified number of the most recent files.
        If you wanted to delete the oldest files, you could pipe the output to the `Remove-Item` cmdlet. For example, let's say you wanted to retain the last 10 files and delete the rest: `Get-LogFilesByPatternAndRetention -LogNameStartsWith "AppLog" -KeepLast 10 | Remove-Item`.
 
    .PARAMETER LogNameStartsWith
        Specifies the beginning of the log file name to search for. This parameter is mandatory.
 
    .PARAMETER LogPath
        Specifies the path to the directory where the log files are located. The default path is "C:\ProgramData\Microsoft\IntuneManagementExtension\Logs".
 
    .PARAMETER KeepLast
        Specifies the number of most recent log files to retain. The default value is 7.
 
    .EXAMPLE
        Get-LogFilesByPatternAndRetention -LogNameStartsWith "AppLog"
 
        Retrieves log files that start with "AppLog" from the default log directory and retains the last 7 files. It will output the log files in descending order based on their last write time.
 
    .EXAMPLE
        Get-LogFilesByPatternAndRetention -LogNameStartsWith "AppLog" -LogPath "D:\Logs" -KeepLast 10
 
        Retrieves log files that start with "AppLog" from the specified log directory and retains the last 10 files. It will output the log files in descending order based on their last write time.
 
    .EXAMPLE
        Get-LogFilesByPatternAndRetention -LogNameStartsWith "AppLog" -KeepLast 5 | Remove-Item
 
        Retrieves log files that start with "AppLog" from the default log directory and retains the last 5 files. It will output the log files in descending order based on their last write time and delete the rest.
 
    .NOTES
        Author: owen.heaume
        Version:
            1.0.0 - Initial release
    #>


    [cmdletbinding()]

    param (
        [parameter(mandatory = $true)]
        [string]$LogNameStartsWith,

        [parameter(mandatory = $false)]
        [string]$LogPath = 'C:\ProgramData\Microsoft\IntuneManagementExtension\Logs',

        [parameter(mandatory = $false)]
        [int]$KeepLast = 7
    )

    Begin {}

    Process {
        $logFiles = Get-ChildItem -Path $LogPath -Filter "$LogNameStartsWith*.log"
        $logFiles | Sort-Object LastWriteTime -Descending | Select-Object -Skip $KeepLast
    }
}