Requirement: Generate a log file and add messages to it to track the execution of a PowerShell script.
When creating PowerShell scripts, it’s often helpful to generate log files to track the progress of the script and diagnose any issues that may arise. Sometimes, we may need to log messages to help us troubleshoot where and what went wrong during the script’s execution or for tracking purposes. This post 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!"How about adding a timestamp to the log file along with the log message?
function Write-Log { param( [string]$Message ) $timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") "$timestamp - $Message" | Out-File -FilePath C:\logs\script.log -Append
}Case 1: Create a Log File from Time Stamp in the Current Directory
Keeping track of events, errors, and other important information is crucial for effective monitoring, troubleshooting, and auditing in PowerShell scripts. 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 of PowerShell logging:

Case 2: Create a Log File in Given Location
Logging is an essential practice in PowerShell scripting, as it allows you to capture valuable information about the execution of your scripts, including success messages, warnings, errors, and other relevant details. 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 $LogFilePathHere is another simplified approach: By default, PowerShell commands’ output is sent to the console. Using the Out-File cmdlet, you can redirect it to a text file.
#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..."The “-Append” switch is used to append output to an existing file. You can also use the redirect operator > allows you to write and >> to append. Another form of logging messages to text files:
#Set the Log File Location
$LogFile = "C:\temp\$($env:computername)_AppLog.log"
#Function to Create a Log File
Function Write-Log { param( [Parameter(Mandatory = $true)][string] $message, [Parameter(Mandatory = $false)] [ValidateSet("INFO","WARNING","ERROR")] [string] $level = "INFO" ) $Timestamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss") Add-Content -Path $LogFile -Value "$timestamp [$level] - $message"
}
#Call the Function to Log a Message
Write-Log -level ERROR -message "String Operation failed"Start-Transcript / Stop-Transcript in PowerShell
The Start-Transcript and Stop-Transcript cmdlets in PowerShell are used to record and save a transcript of your PowerShell session to a file. This is particularly useful for logging and documenting your PowerShell activities, troubleshooting, or creating a record of your commands and their output.
Here’s how you can use these cmdlets:
Start-Transcript:
Start-Transcript -Path "C:\Transcripts\Session.log"
This command will start recording your PowerShell session and save the transcript to the specified file.
Stop-Transcript:
To stop recording your PowerShell session, use the Stop-Transcript cmdlet. Example:
This command will stop the recording and save the transcript file.
Here’s an example that demonstrates the usage of Start-Transcript and Stop-Transcript:
# Start the transcript
Start-Transcript -Path "C:\Transcripts\Session.log" -Verbose
# Perform some PowerShell commands
Get-Date
Get-Service| Where-Object { $_.Status -eq "Running" }
Write-Host "This is a sample message."
# Stop the transcript
Stop-TranscriptIn this example:
- The
Start-Transcriptcmdlet is used to start recording the PowerShell session and save the transcript to the file “C:\Transcripts\Session.log”. - Various PowerShell commands are executed, such as
Get-Date,Get-Service, andWrite-Host. - The
Stop-Transcriptcmdlet is used to stop the recording and save the transcript file.
After running these commands, you will find a file named “Session.log” in the specified location (“C:\Transcripts\”). This file will contain a record of the commands executed and their output during the PowerShell session.
Best practices for writing to log files in PowerShell
Here are some best practices for writing to log files in PowerShell, include:
- Use meaningful and descriptive log messages.
- Include relevant information such as timestamps, script names, and error details.
- Use appropriate log levels (e.g., informational, warning, error) to categorize log entries.
- Implement proper error handling and logging of exceptions.
- Regularly rotate or archive log files to prevent them from growing too large.
- Secure access to log files to protect sensitive information.
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. Using the built-in “Out-File” or “Add-Content” cmdlets makes it 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 essential to test the log file to ensure it works as expected and contains the information you need. Overall, using log files can greatly improve the maintainability and troubleshooting of your PowerShell scripts.
Refer to this related post on sending PowerShell Output: How to send PowerShell cmdlet output to a File using the Out-File cmdlet?
What is the purpose of logging in PowerShell scripts?
Logging in PowerShell scripts helps track the progress of the script, diagnose issues, and troubleshoot errors that may occur during execution.
How can I create a log file in a PowerShell script?
How can I handle errors and log them in PowerShell scripts?
How can I enable PowerShell logging for all commands executed?
How do I log messages from within a script?
You can use the Add-Content cmdlet to write custom messages to a log file from within a script: $logfile = "C:\Logs\scriptlog.txt"
Add-Content -Path $logfile -Value "Script started at $(Get-Date)"
#Your script code here
Add-Content -Path $logfile -Value "Script ended at $(Get-Date)"
How can I include timestamps in my PowerShell log file entries?
How can I create a new log file for each PowerShell session?
How do I clear a log file before writing new data?
To clear a log file before writing new data, you can use the Clear-Content cmdlet: Clear-Content -Path "C:\Logs\mylog.txt"
How can I append messages to an existing log file?
What is the difference between Out-File and Add-Content cmdlets?
The Out-File cmdlet is used to write output to a file, replacing its content if it already exists (Use the Append switch to add content to the end). The Add-Content cmdlet, on the other hand, appends the output to the end of the file, preserving its existing content.
Why Logging Matters in PowerShell
Logging is the process of recording events and data to a file or other output streams. In PowerShell, logging is vital for debugging purposes, monitoring script execution, and ensuring that you have a record of what actions were taken and when.
There are various ways you can create a log file in PowerShell.
Method 1: Start-Transcript and Stop-Transcript
PowerShell offers a built-in cmdlet called Start-Transcript to log a PowerShell session. This cmdlet starts recording all interactions with the console and saves them to a specified file. To stop recording, use the Stop-Transcript cmdlet.
Here is an example.
Start-Transcript -Path "C:\Logs\PowerShell_Log.txt"
# Your script commands here
Stop-TranscriptOnce you execute the above PowerShell script, it will create a log file and write the particular text in the above specified path.
Method 2: Out-File Cmdlet
The Out-File cmdlet in PowerShell is another way to write output directly to a log file. You can use it to append or overwrite data in a log file.
Here is a complete example:
"Information: Logging started." | Out-File -FilePath "C:\Logs\ScriptLog.txt" -Append
# Your script commands here
"Information: Logging completed." | Out-File -FilePath "C:\Logs\ScriptLog.txt" -AppendThis method allows you to selectively log information to your file, providing more control over what gets logged.
Method 3: Add-Content Cmdlet
Add-Content is a cmdlet in PowerShell that lets you append content to a log file without overwriting the existing content. This is useful for adding log entries as your script runs.
Here is a complete example.
Add-Content -Path "C:\Logs\ScriptLog.txt" -Value "Script has started at $(Get-Date)"
# Your script commands here
Add-Content -Path "C:\Logs\ScriptLog.txt" -Value "Script has finished at $(Get-Date)"This cmdlet is similar to Out-File -Append, but it’s specifically designed for adding text to files, making it ideal for logging purposes.
Method 4: Custom Logging Function
You can create a custom function to handle logging in PowerShell. This function can include parameters for the log message, log file path, and other options like timestamping.
Here’s a simple function that writes log entries to a specified file:
function Write-Log { Param ( [string]$LogString, [string]$LogFile ) Add-Content -Path $LogFile -Value $LogString
}
# Usage
$LogFile = "C:\MyFolder\script.log"
Write-Log "This is a log entry" -LogFile $LogFileThis function uses the Add-Content cmdlet to append the log string to the specified log file.
You can see the output in the screenshot below after I executed the PowerShell script using VS code.

function Write-Log { param ( [string]$LogPath, [string]$Message ) $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logEntry = "$timestamp - $Message" Add-Content -Path $LogPath -Value $logEntry
}
$LogPath = "C:\MyFolder\CustomLog.txt"
Write-Log -LogPath $LogPath -Message "Script started"
# Your script commands here
Write-Log -LogPath $LogPath -Message "Script ended"This will prepend the current date and time to each log entry, formatted as YYYY-MM-DD HH:MM:SS.
Method 5: PSFramework
Here is a complete example.
Import-Module PSFramework
Set-PSFLoggingProvider -Name logfile -Enabled $true -LogPath "C:\Logs\PSFrameworkLog.txt"
Write-PSFMessage "Script started" -Level Important
# Your script commands here
Write-PSFMessage "Script ended" -Level ImportantThis method requires the installation of the PSFramework module but offers a professional logging setup that can be essential for enterprise-level scripts.
Best Practices for PowerShell Logging
- Consistency: Use a consistent log file naming convention to make it easier to locate and analyze logs.
- Timestamps: Include timestamps in your logs to provide context for when events occurred.
- Log Levels: Implement log levels (e.g., DEBUG, INFO, WARN, ERROR) to categorize the importance of log messages.
- Error Handling: Include logging within try/catch blocks to capture exceptions and errors.
- Log Rotation: Implement log rotation to prevent log files from becoming too large and unmanageable.
- Sensitive Data: Be cautious about logging sensitive information. Always sanitize logs if they may contain passwords, PII, or other sensitive data.
Conclusion
I hope that now, from this tutorial, you can create and write a log file in PowerShell using the above-mentioned methods.
You may also like:

