PoshCode Archive  Artifact Content

Artifact df1c4c28a79d40c8db14b2af89450544515f6ebe5535cec200e52e95713d9cbb:

  • File Trace-Message.ps1 — part of check-in [3698273392] at 2018-06-10 14:04:41 on branch trunk — A function to print trace messages with timings. (user: Joel Bennett size: 1944)

# encoding: ascii
# api: powershell
# title: Trace-Message
# description: A function to print trace messages with timings.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Trace-Message
# x-poshcode-id: 5948
# x-archived: 2016-09-10T00:11:40
# x-published: 2016-07-29T21:23:00
#
# Note that you should always call it first in a function where you care about the timings, and call it last with -KillTimer to clean up.
#
    function Trace-Message {
        #.Synopsis
        #   A function to print trace messages with timings.
        #.Notes
        #   Does NOT currently support nested traces for the timer function
        #   You always need to call Trace-Message immediately upon entry
        #   And then call Trace-Message -KillTimer immediately upon exit
        [CmdletBinding()]
        param(
            [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [string]$Message,

            [switch]$AsWarning,

            [switch]$ResetTimer,

            [switch]$KillTimer
        )
        begin {
            if($Script:TraceVerboseTimer -eq $null) {
                $Script:TraceVerboseTimer = New-Object System.Diagnostics.Stopwatch
                $Script:TraceVerboseTimer.Start()
            } 
            elseif($ResetTimer) 
            {
                $Script:TraceVerboseTimer.Restart()
            }
        }

        process {
            $Message = "$Message - at {0} Line {1} | {2}" -f (Split-Path $MyInvocation.ScriptName -Leaf), $MyInvocation.ScriptLineNumber, $TraceVerboseTimer.Elapsed

            if($AsWarning) {
                Write-Warning $Message
            } else {
                Write-Verbose $Message
            }
        }

        end {
            if($KillTimer) {
                $Script:TraceVerboseTimer.Stop()
            }
        }
    }