[PowerShell] Log Functions for Custom Modules

Reading Time: 4 minutes

Logging activity within custom functions can often be repetitive and messy. The following two log functions for custom modules are intended to make activity logging simple and easy. Include these two functions in your module, update the default LogPath parameter and you’re well on your way.

The New-Log function is designed to be embedded into the functions of your custom module. The only mandatory parameter is the log type. Other information such as the module name, function name, and current user is automatically captured and logged. New log entries are automatically appended to a daily log located at the location specified by LogPath. If no log path is provided, the function will use the default LogPath location embedded in the function.


   This cmdlet creates a new log entry and appends it to the daily log file on the specified log server.
   This cmdlet creates a new log entry and appends it to the daily log file on the specified log server.
   New-Log -Type "Pass"
   New-Log -Type "Fail" -Target TargetComputerName
   New-Log -Type "Fail" -Target TargetComputerName -Throw
  This code is provided "as is" and with no expressed guarantees. The code provider makes no representations or warranties of any kind concerning 
the safety, suitability, inaccuracies, typographical errors, or other harmful components of this code. There are inherent dangers in the use of 
any code, and you are solely responsible for determining whether this code is compatible with your equipment and other software installed on your 
equipment. You are also solely responsible for the protection of your equipment and backup of your data, and the provider will not be liable for 
any damages you may suffer in connection with using, modifying, or distributing this code.

Justin C.

Function New-Log
        #Log Entry Type
        [ValidateSet("Pass", "Fail", "Info", "Test")]
        [Parameter(Mandatory, Position=0, ValueFromPipelineByPropertyName)]
        [String] $LogType,

        #Target Object
        [Parameter(Position=1, ValueFromPipelineByPropertyName)]
        [String] $Target,

        [Alias("Remark", "Comment", "Comments", "Note", "Notes")]
        [Parameter(Position=2, ValueFromPipelineByPropertyName)]
        [String] $Remarks="None",

        #Error Message
        [Parameter(Position=3, ValueFromPipelineByPropertyName)]

        #Log Path
        [Parameter(Position=4, ValueFromPipelineByPropertyName)]
        [String] $LogPath = "\LogServerNameLogs",

        [Switch] $WriteHost,

        [Switch] $Throw
    Begin {
        $DateFormat = Get-Date -UFormat %b-%d-%Y
        $LogFile = Join-Path $LogPath "$DateFormat.csv"
        If(Test-Path $LogPath -ErrorAction SilentlyContinue){}
        Else{New-Item -ItemType Directory -Path $LogPath}
    Process {
        $Stack = (Get-PSCallStack | Select-Object -Property *)[1]
        #If ($null -ne $Parameters){$ParameterString = Convert-HashToString $PsBoundParameters}Else{$ParameterString="None"}
        If ($null -eq $Target){$Target = "None"}
        If ($null -eq $Stack.Arguments) {$FunctionArguments = "None"}Else{$FunctionArguments = $Stack.Arguments}
        $LogEntry = New-Object -TypeName PSObject -Property ([Ordered]@{
            Type = $LogType;
            Module = $Stack.ScriptName;
            Function = $Stack.Command;
            Target = $Target;
            Arguments = $FunctionArguments;
            User = $env:USERNAME;
            Computer = $env:COMPUTERNAME;
            Timestamp = Get-Date -Format G;
            ErrorData = $ErrorMsg;
            Remarks = $Remarks;
        If ($Target){
            If ($WriteHost){Write-Host "$Target - $Remarks"}
            Write-Verbose "LOGGED: $LogType Event for $($Stack.Command) on $Target logged to $LogFile"
        } Else {
            If ($WriteHost){Write-Host "$Remarks"}
            Write-Verbose "LOGGED: $LogType Event for $($Stack.Command) logged to $LogFile"
        $LogEntry | Export-Csv $LogFile -Append -NoTypeInformation -Force
	End {
        If ($Throw) {Throw "$($Stack.Command) - $Remarks" }

Function Convert-HashToString 

    Param (
    [System.Collections.Hashtable] $Hash
    $HashString = "@{"
    $Keys = $Hash.Keys
    foreach ($Key in $Keys) {
        $Value = $Hash[$Key]
        If ($Key -match "s"){$HashString += "'$Key'" + "=" + "'$Value'" + ";"}
        Else {$HashString += $Key + "=" + "'$Value'" + ";"}
    $HashString += "}"
    return $HashString
Function Convert-ArrayToString 

    Param (
    [System.Array] $Array
    $ArrayString = $Array.join(", ")
    return $ArrayString

Get-Log Function (Next Page)

Liked it? Take a second to support Justin on Patreon!
Pages: 1 2
%d bloggers like this: