How to Create a Log File in PowerShell?

As a PowerShell developer or administrator, you need to create and manage log files. Logging is essential for debugging and monitoring your PowerShell scripts. In this tutorial, I will explain how to create a log file in PowerShell using various methods. I will also show you how to write to log files in PowerShell.

PowerShell Log File

PowerShell provides various ways to create and manage log files. As an administrator or a developer, you can log system events, application errors, or custom messages. These logs helps in keeping a record of what your scripts are doing, which is invaluable for debugging and auditing purposes.

Create a Log File in PowerShell

To create a log file in PowerShell, you can use the Out-File cmdlet. Here’s an example to create and write to a log file in PowerShell.

# Define the log file path
$logFile = "C:\Logs\MyLogFile.log"

# Create a new log file or overwrite an existing one
"Log Entry: Script started at $(Get-Date)" | Out-File -FilePath $logFile -Force

This script creates a log file named MyLogFile.log in the C:\Logs directory and writes the current date and time as the first log entry.

I executed the above PowerShell script, and you can see the exact output in the screenshot below:

powershell log file

You can also modify the script to check if the folder already exists. If it does not, it will create it.

# Define the log file path
$logFile = "C:\Logs\MyLogFile.log"

# Ensure the directory exists
if (-not (Test-Path -Path (Split-Path -Path $logFile))) {
    New-Item -Path (Split-Path -Path $logFile) -ItemType Directory
}

Check out Add Date to Filename Using PowerShell

Write to Log File in PowerShell

Once a log file is created in PowerShell, you can append new entries to it using the Add-Content cmdlet. This is useful for logging multiple events or messages during the execution of your script.

Here is the complete PowerShell script.

# Define the log file path
$logFile = "C:\Logs\MyLogFile.log"

# Function to write a log entry
function Write-Log {
    param (
        [string]$message
    )

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    $logMessage | Add-Content -Path $logFile
}

# Example usage
Write-Log "Script started"
Write-Log "Performing some task"
Write-Log "Script ended"

This script defines a Write-Log function that appends timestamped log entries to the log file.

You can see the exact output in the screenshot below:

powershell output to log file

Read Sort Files by Date in PowerShell

Add Timestamps to Log Entries in PowerShell Log File

It is very important to add timestamps in log entries in a PowerShell log file. This helps to find the sequence of events for debugging purposes. PowerShell makes it easy to add timestamps to your log entries. The Get-Date cmdlet can be used to generate a timestamp in various formats.

Here is the complete PowerShell script.

# Function to write a log entry with a timestamp
function Write-Log {
    param (
        [string]$message
    )

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp - $message"
    $logMessage | Add-Content -Path $logFile
}

This function generates a timestamp in the format yyyy-MM-dd HH:mm:ss and prepends it to each log message. This ensures that every log entry is timestamped, making it easier to trace the sequence of events.

Check out How To Create File If Not Exists In PowerShell?

Add Different Types of Logs to PowerShell Log File

In real-world scenarios, you might need to include different log levels such as INFO, WARN, ERROR, etc. Here’s an example that explains how to add different types of log messages in a log file:

# Define the log file path
$logFile = "C:\Logs\MyAdvancedLogFile.log"

# Function to write a log entry with log levels
function Write-Log {
    param (
        [string]$message,
        [string]$level = "INFO"
    )

    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "$timestamp [$level] - $message"
    $logMessage | Add-Content -Path $logFile
}

# Example usage
Write-Log "Script started" "INFO"
try {
    # Simulate a task
    Write-Log "Performing some task" "INFO"
    throw "An error occurred"
} catch {
    Write-Log $_ "ERROR"
}
Write-Log "Script ended" "INFO"

Check out Append Text to a File in PowerShell

Log the Entire PowerShell Session

Sometimes, you might want to log an entire PowerShell session, then you can use the Start-Transcript cmdlet. It captures all command outputs and errors, providing a complete log of the session.

# Define the log file path
$logFilePath = "C:\Logs\SessionTranscript.txt"

# Start the transcript
Start-Transcript -Path $logFilePath

# Sample commands
Write-Output "[$(Get-Date)] - Starting the healthcare data processing script."
# ... additional script commands ...

# Stop the transcript
Stop-Transcript

The Start-Transcript cmdlet starts recording the session, and Stop-Transcript stops the recording.

Conclusion

In this tutorial, I explained how to create a log file in PowerShell and also explained how to write to a log file in PowerShell. You also learned how to add timestamps to log entries in PowerShell. Do let me know in the comment below if this tutorial helps you.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.