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?

When creating PowerShell scripts, it’s often useful to create log files to track the progress of the script and to diagnose any issues that may arise. Sometimes, We may need to log messages to help us troubleshoot where and what went wrong during the execution of the script, or for tracking purposes. In this post, we will discuss how to create a log file in a PowerShell script.

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 a 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 stamps 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 for 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

Here is another simplified approach:

#Function to Add Content to Log File
Function Write-Log {

  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogFilePath, [Parameter(Mandatory=$true)][string]$Message)
  
  Process{
    #Add Message to Log File with timestamp
    "$([datetime]::Now) : $Message" | Out-File -FilePath $LogFilePath -append;
  
    #Write the log message to the screen
    Write-host $([datetime]::Now) $Message
  }
}

#Usage
Write-Log "C:\Temp\Log.txt" "Script execution started..."
Sleep(5)
Write-Log "C:\Temp\Log.txt" "Script is being executed..."
Sleep(5)
Write-Log "C:\Temp\Log.txt" "Script execution Completed..."

Conclusion:

Creating a log file in a PowerShell script can be very useful for tracking the progress of the script, and for debugging any issues that may arise. By using the built-in “Out-File” or “Add-Content” cmdlets, it’s easy to create a log file and write output to it. The log file can be configured to append new information to the end of the file each time the script is run. It’s important to test the log file to ensure that it is working as expected and contains the information you need. Overall, using log files can greatly improve the maintainability and troubleshooting of your PowerShell scripts.

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

3 thoughts on “How to Create a Log File in PowerShell Script?

  • Hi naman
    How can I safe a log messages out of an array? Like:
    Foreach ($document in $Files)
    #Log Start Time of the Script
    {
    $StartTime = (Get-Date)
    Log-Message “Title is: $Files.Title” -LogFilePath $LogFilePath
    Log-Message “Deleted from: $Files.DeletedDate” -LogFilePath $LogFilePath
    Log-Message “Author is: $Files.AuthorName” -LogFilePath $LogFilePath
    Log-Message “Document lays here: $Files.DirNameName” -LogFilePath $LogFilePath
    }

    Reply
  • Hi, I am facing issue in csv column of my log file, not able to get leading zeros, I am using add-content & set-content cmdlet to create log file , but unable to change the data type of column as it is taking value as int but I want to write it as a string . Need your help in this issue. Kindly look into that. Thanks in advance

    Reply
    • To format the value in three digits, try this: $Value = $Value.ToString(“000”)

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *