Looking back to the thread of the past weeks [1], I think it may be better to spend some minute more to create a separate library for loggin which can be reusable. Indeed logging is one of the most common activities and it would be great this functionality can stay in a separate file which I can just invoke in the context of my script when needed.
For this reason I’ll create a new ps1 file called XinLog where put all the logging logics:
################# XinLog 1.0 ######################
# Use this library to log easely on file and screen
# In Parameters MANDATORY
# - $LogString [STRING] Message to log
# The log on file will create file a file in the same directory of the caller
###################################################
# Get the current Directory
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
#Set the file log name
$Logfile = "$myDir\XinLog_$($env:computername)_$((Get-Date).toString("yyyyMMdd_HHmmss")).log"
#begin FUNCTIONS
function Write-Log
{
Param (
[Parameter(Mandatory)]
[string]$LogString
)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp - $LogString"
Add-content $LogFile -value $LogMessage
Write-Host $LogString -ForegroundColor White
}
#end FUNCTIONS
Actually I did’t do too much, I just extracted the lines related to logging from previous file moving the Write-Log function body which is the log writer.
Now the question is: How can I use Write-Log function if now it is in a separate file? The answer is really straightforward since as it is happening in a large part of languages it is possible to include a script in another one also in PoweShell. To do this we are leveraging on the “dot source notation” (you can find more information here [2]). In our scenario the original file Conto2.3 will change as below:
########### CONTO 2.3.1 ############
# First test
####################################
##### Inclueded Libraries ##########
# Get the current Directory
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# Files included
. "$myDir\XinLog.ps1" # Include the file logs
####################################
#begin BODY
Write-Log "Text to write"
#end BODY
Here [3] you can find also a GitHub project I created for this purpose.
[1] https://www.beren.it/2022/01/07/conto2-3-logging-with-powershell-get-started/