PowerShell Logging Function

I am writing a lot of Scripts during the Day and weeks, so I often copy some basic Functions from other Script to speed up the process of creating a PowerShell.

One of them is always a Logging Function I need for my Scripts, so I decided to post this here for you.

There are some Variables at the beginning followed by the Function

In the End, we will remove older LogFiles from the Folder

The Script

#region Parameters
[string]$LogPath = "D:\_SCOWorkingDir\PowerShell\Warranty Info" #Path to store the Lofgile
[string]$LogfileName = "GetWarranty" #FileName of the Logfile
[int]$DeleteAfterDays = 10 #Time Period in Days when older Files will be deleted

#endregion Parameters

#region Function
function Write-TechguyLog {
    [CmdletBinding()]
    param
    (
        [ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR')]
        [string]$Type,
        [string]$Text
    )

    # Set logging path
    if (!(Test-Path -Path $logPath)) {
        try {
            $null = New-Item -Path $logPath -ItemType Directory
            Write-Verbose ("Path: ""{0}"" was created." -f $logPath)
        }
        catch {
            Write-Verbose ("Path: ""{0}"" couldn't be created." -f $logPath)
        }
    }
    else {
        Write-Verbose ("Path: ""{0}"" already exists." -f $logPath)
    }
    [string]$logFile = '{0}\{1}_{2}.log' -f $logPath, $(Get-Date -Format 'yyyyMMdd'), $LogfileName
    $logEntry = '{0}: <{1}> {2}' -f $(Get-Date -Format dd.MM.yyyy-HH:mm:ss), $Type, $Text
    Add-Content -Path $logFile -Value $logEntry
}
#endregion Function

Write-TechguyLog -Type INFO -Text "START Script"




#Clean Logs
Write-TechguyLog -Type INFO -Text "Clean Log Files"
$limit=(Get-Date).AddDays(-$DeleteAfterDays)
Get-ChildItem -Path $LogPath -Filter "*$LogfileName.log" | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force


Write-TechguyLog -Type INFO -Text "END Script"

GitHub Repo

Here is the Github Repo with the latest Version: Seidlm/PowerShell-Template—Logging-Function: PowerShell Template – Logging Function (github.com)

Michael Seidk aka Techguy

2 thoughts on “PowerShell Logging Function”

  1. Pingback: Update all PowerShell Modules with one Script - TechGuy

  2. Pingback: powershell logging function – cellhow

Leave a Comment

Your email address will not be published. Required fields are marked *

*