📜 ⬆️ ⬇️

Powershell - logging to file

Good day, $ username!

I want to share with you a function that I use instead of the usual display of information on the screen or just writing to a file.

The function was written in order to display information on the screen and in the log (textual), intended to replace the standard write-host.
')

Of goodies:


The function is declared globally, which means that within one session it is enough to initialize it once - read the launch file with it.

Use options:
write-log "Hello !"
14.07.2011 00:22:15 info Hello !
write-log -message "Hello !" -type warning

write-log -message "Hello !" -type error -silent

, :
write-log -message "Hello !" -type CustomType logfile c:\enter\your\path\here.log


The number of errors and warnings (for the entire session or until the variables are manually reset) are stored in $ errorcount and $ warningcount .

Personally, I have this function stored in the set-functions.ps1 file, and in the scripts I call it like this:

The very beginning of any (where necessary) of my script:
 $ver="0.1" $ProgrammName="SomeScriptName" try { #          ./Set-Functions.ps1 #  $global:logfilename = "log`\"+ $ProgrammName +".log" write-log "$ProgrammName (ver $ver) started." } catch { return "Error loading functions Set-Functions.ps1" } 


The body of the write-log function:
 $ver = "0.4" $dt=Get-Date -Format "dd-MM-yyyy" New-Item -ItemType directory log -Force | out-null #    $global:logfilename="log\"+$dt+"_LOG.log" [int]$global:errorcount=0 #   [int]$global:warningcount=0 #   function global:Write-log #     -    . {param($message,[string]$type="info",[string]$logfile=$global:logfilename,[switch]$silent) $dt=Get-Date -Format "dd.MM.yyyy HH:mm:ss" $msg=$dt + "`t" + $type + "`t" + $message #: 01.01.2001 01:01:01 [tab] error [tab]  Out-File -FilePath $logfile -InputObject $msg -Append -encoding unicode if (-not $silent.IsPresent) { switch ( $type.toLower() ) { "error" { $global:errorcount++ write-host $msg -ForegroundColor red } "warning" { $global:warningcount++ write-host $msg -ForegroundColor yellow } "completed" { write-host $msg -ForegroundColor green } "info" { write-host $msg } default { write-host $msg } } } } 


This example has only one drawback - it is “synchronous”, that is, it does not handle the problem of simultaneous recording to the log file. Who knows how to change this, please in the comments.

Source: https://habr.com/ru/post/124105/


All Articles