# Write-Trace # # Simple Module to have a general tracing functino for powershell scripts. # write-output, write-verbose and start-transcript are slowing down large scripts and should be uses for screen interactivity # write-trace adds a commandlet to send any kind og details to a file or the console in a formatted ways # # 20171019 frank@carius.de initial version write-host "Write-Trace Module loading" # this variabels are local for the module and not exposed to the importing script [string]$tracefilename = "" [int]$tracelevelfile=5 [int]$tracelevelcon=5 function Set-TraceParameter { # Configure parameters of the trace writer param ( [string]$tracefilename, [int]$levelfile, [int]$levelcon ) if ($tracefilename) { write-verbose "Update Trace Parameter tracefilename with $($tracefilename)" $script:tracefilename=$tracefilename } if ($levelfile) { $script:tracelevelfile=$levelfile write-verbose "Update Trace Parameter tracelevelfile with $($levelfile)" } if ($levelcon) { $script:tracelevelcon=$levelcon write-verbose "Update Trace Parameter tracelevelcon with $($levelcon)" } } function Get-TraceParameter { # return the current parameter of the trace writer New-Object PSObject -Property @{ tracefilename = $script:tracefilename tracelevelfile=$script:tracelevelfile tracelevelcon=$script:tracelevelcon } } function Write-Trace { # Write message to the target [CmdletBinding()] Param ( [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullOrEmpty()] [string]$Message, # message to wrinte [Parameter(Mandatory=$false)] [int]$Level=0 # level of the specific message 0=info, 1=error, 2=warning 3.. = debuglevel ) Begin { } Process { # Write message to error, warning, or verbose pipeline and specify $LevelText if (($level -le $script:tracelevelfile) -or (($level -le $script:tracelevelcon))) { $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" switch ($Level) { 0 {$Message = "$($timestamp) LOG $($Message)"} 1 {$Message = "$($timestamp) ERR $($Message)" ; Write-Error $Message} 2 {$Message = "$($timestamp) WARN $($Message)" ; Write-Warning $Message} 3 {$Message = "$($timestamp) INFO $($Message)" ; Write-Verbose $Message} default {$Message = "$($timestamp) DBG$($Level) $(".."*($Level-2))$($Message)"} } if (($level -le $script:tracelevelfile) -and ($script:tracefilename)) { # send trace to file $Message | Out-File -FilePath $script:tracefilename -Append } if ($level -le $script:tracelevelcon) { # send trace to console write-host $Message } } } End { } } write-host "Write-Trace Module loaded"