Sunday 8 March 2020

Powershell create Log file. Write-Log

Hey,

Lets look at a small snippet that can add some details to log file when the script is being executed.
This can be used as a function in the script and the log file would be appended with the information.

The script could be customized further based on your needs.



#Define a log path
$LogFile = "$env:USERPROFILE\log.txt"
function Write-Log
{
    [CmdletBinding()]
        Param(
        [Parameter(Mandatory=$False)]
        [ValidateSet("DEBUG","INFO","WARN","ERROR","CRITICAL")]
        [String]
        $Level = "INFO",

        [Parameter(Mandatory=$True)]
        [string]
        $Message
        )

    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
    $DLog = "$Stamp $Level $Logentry"
    Add-Content -Path $LogFile -Value $DLog -Force
}



Note that the "Message" is mandatoy parameter that has to be passed to the function while calling it and 'Level' is optional and defaults to 'INFO' if not specified.


How to call the function in your script samples based on the scenario.

    #Example execution
    Write-Log -Level WARN -Message "Warning Log"
    Write-Log -Level DEBUG -Message "Debug Log"
    Write-Log -Level INFO -Message "Info Log"

View the Log or pull the log at the end of the script.

invoke-item "$env:USERPROFILE\log.txt"


Output


-Happy Scripting


No comments:

Post a Comment