How to Create a Log File in PowerShell Script?

Requirement: Generate a log file and add messages to it to track the execution of a PowerShell script

How to Create a Log File in PowerShell?
We may need to log messages to help us troubleshooting where and what went wrong during the execution of the script. Sometimes, for tracking purposes. The simplest way to generate log files by adding content to a text file is:
Function Log-Message([String]$Message)
{
    Add-Content -Path "C:\Temp\Log.txt" $Message
}

Log-Message "Beginning exeuction of the script:"
Log-Message "Exeucting of the script..."
Log-Message "Completed exeuction of the script!"

Case 1: Create Log File from Time Stamp in the Current Directory
Let's create a log file based on the current timestamp and log messages prepending time stamp to it.
Function Log-Message()
{
 param
    (
    [Parameter(Mandatory=$true)] [string] $Message
    )

    Try {
        #Get the current date
        $LogDate = (Get-Date).tostring("yyyyMMdd")

        #Get the Location of the script
        If ($psise) {
            $CurrentDir = Split-Path $psise.CurrentFile.FullPath
        }
        Else {
            $CurrentDir = $Global:PSScriptRoot
        }

        #Frame Log File with Current Directory and date
        $LogFile = $CurrentDir+ "\" + $LogDate + ".txt"

        #Add Content to the Log File
        $TimeStamp = (Get-Date).toString("dd/MM/yyyy HH:mm:ss:fff tt")
        $Line = "$TimeStamp - $Message"
        Add-content -Path $Logfile -Value $Line

        Write-host "Message: '$Message' Has been Logged to File: $LogFile"
    }
    Catch {
        Write-host -f Red "Error:" $_.Exception.Message 
    }
}

#Call the function to Log messages
Log-Message "Script Execution Started"
Log-Message "Script is being Executed"
Log-Message "Script Execution Completed"
and the result
powershell generate log file

Case 2: Create a Log File in Given Location 
This time, let's create a log file to the given location.
Function Log-Message()
{
 param
    (
    [Parameter(Mandatory=$true)] [string] $Message,
    [Parameter(Mandatory=$true)] [string] $LogFilePath
    )

    Try {
        #Add Content to the Log File
        Add-content -Path  $LogFilePath -Value $Message
        Write-host "Message: '$Message' Has been Logged to File: $LogFilePath" -f Yellow
    }
    Catch {
        Write-host -f Red "Error:" $_.Exception.Message 
    }
}

#Set Location for Log File
$LogFilePath = "C:\Temp\AppLog.txt"

#Ensure the Parent Folder for Log File
$FolderPath= Split-Path $LogFilePath
If(!(Test-Path -path $FolderPath))  
{  
    New-Item -ItemType directory -Path $FolderPath | Out-Null
}

#Delete the Log file if exists
If(Test-Path $LogFilePath) 
{
    Remove-Item $LogFilePath
}

#Log Start Time of the Script
$StartTime =   (Get-Date)
Log-Message "Script Started at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')" -LogFilePath $LogFilePath

#Pause for 2 Seconds
Sleep 2

#Log End Time
$EndTime =   (Get-Date)
Log-Message "Script Ended at: $(Get-date -format 'dd/MM/yyy hh:mm:ss tt')" -LogFilePath $LogFilePath

#Get Elapsed Time
$ElapsedTime = ($EndTime - $StartTime).Seconds
Log-Message "Script Execution Time: $ElapsedTime Seconds" -LogFilePath $LogFilePath

How to Create a Log File in PowerShell Script? How to Create a Log File in PowerShell Script? Reviewed by Salaudeen Rajack on June 11, 2019 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.