Functions/Logging/New-FpsLogFile.ps1


<#
    .SYNOPSIS
    Creates a new log file and removes previous logfiles if the amount of logfiles exceedes $LogFilesToPreserve
    .DESCRIPTION
    Creates a logfile, default location is c:\ProgramData\4ps\[$LogFileFolder]\yyyy-MM-dd_HH.mm.ss_[$LogFileNameSuffix].log
    .EXAMPLE
    New-FpsLogFile -LogFileFolder 'MyScript' -LogFileNameSuffix 'EnvironmentA'
    .EXAMPLE
    New-FpsLogFile -LogFilePath 'c:\temp\myTempLog'
    .EXAMPLE
    New-FpsLogFile -LogFileFolder 'MyScript' -LogFileNameSuffix 'EnvironmentA' -LogFilesToPreserve 1
#>

function New-FpsLogFile {
    [CmdletBinding(DefaultParameterSetName='Default')]
    param (
        # The LogFile base path. Default 'C:\ProgramData\4ps'.
        [Parameter(ParameterSetName='Default')]
        [string] $LogFileParent = (Join-Path -Path $env:ProgramData -ChildPath '4ps'), 
        
        # The folder name for the logfiles. E.g. 'MyScript'
        [Parameter(ParameterSetName='Default', Mandatory=$true)]
        [string] $LogFileFolder,
        
        # The path to the folder to store logfiles. E.g. 'C:\ProgramData\4ps\MyScript'.
        [Parameter(ParameterSetName='LogFilePath', Mandatory=$true)]
        [string] $LogFilePath,

        # The Suffix to add to the default logfile name. E.g. 'BCS180Test'.
        # Suffix will be added to the default logfile name: 'yyyy-MM-dd_HH.mm.ss_[Suffix].log'
        [string] $LogFileNameSuffix = 'Fps',

        # The amount of logfiles to preserve.
        [int] $LogFilesToPreserve = 10
    )
    
    
    if(-not $LogFilePath){
        $LogFilePath = Join-Path -Path $LogFileParent -ChildPath $LogFileFolder
    }

    # Create logfile
    $LogFile = Join-Path -Path $LogFilePath -ChildPath ('{0}_{1}.log' -f 
        (Get-Date).ToString('yyyy-MM-dd_HH.mm.ss'), 
        $LogFileNameSuffix)

    New-Item -Path $LogFile -ItemType File -Force | Out-Null

    # Remove old logfiles
    $Regex = '.*_{0}\.log' -f $LogFileNameSuffix
    $LogFiles = Get-ChildItem $LogFilePath -File -Filter '*.log' | Where-Object -Property Name -Match $Regex
    if($LogFiles.Count -gt $LogFilesToPreserve){
        $Exclude = $LogFiles | Sort-Object -Property CreationTime -Descending | Select-Object -First $LogFilesToPreserve
        $LogFiles | Where-Object {$_.FullName -notin $Exclude.FullName} | Remove-Item -Force -ErrorAction SilentlyContinue
    }

    $LogFile
}

Export-ModuleMember -Function New-FpsLogFile