How to Create a Log File using PowerShell?

As an IT professional managing servers for a US-based company, I recently encountered a situation where I needed to track the execution of a critical PowerShell script. To ensure easier troubleshooting, I implemented logging functionality in my script. In this tutorial, I will explain how to create a log file using PowerShell. By analyzing log files, you can monitor the performance and behavior of your PowerShell scripts over time.

Follow the below steps to create a log file using PowerShell.

Step 1: Define the Log File Path and Name

To create a log file, we first need to determine its location and name. In this example, let’s assume we want to store the log file in the “D:\Logs” directory, and the file name should include the name of the computer running the script. Here’s how we can achieve that in PowerShell:

$logDirectory = "D:\Logs"
$logFileName = "Log_$($env:COMPUTERNAME)_$(Get-Date -Format 'yyyyMMdd').log"
$logFilePath = Join-Path -Path $logDirectory -ChildPath $logFileName

In this code snippet:

  • We define the $logDirectory variable to specify the directory where the log file will be stored.
  • The $logFileName variable is constructed using the $env:COMPUTERNAME environment variable to include the computer name and the current date in the format “yyyyMMdd”.
  • Finally, we use the Join-Path cmdlet to combine the $logDirectory and $logFileName to create the complete $logFilePath.

Read PowerShell Copy-Item Cmdlet to Copy Files and Folders

Step 2: Create the Log File

Now that we have the log file path, let’s create the log file using PowerShell’s New-Item cmdlet:

New-Item -Path $logDirectory -Name $logFileName -ItemType File -Force

This command creates a new file with the specified $logFileName in the $logDirectory. The -Force parameter ensures that if the file already exists, it will be overwritten.

Step 3: Write to the Log File

To write messages to the log file, we can use PowerShell’s Add-Content cmdlet. Here’s an example of how to log a message:

$message = "Script execution started."
Add-Content -Path $logFilePath -Value $message

In this code snippet:

  • We define the $message variable to hold the log message we want to write.
  • The Add-Content cmdlet is used to append the $message to the log file specified by $logFilePath.

Read How to Get File Size Using PowerShell?

Step 4: Add Timestamp to Log Entries

To make the log file more informative, it’s a good practice to include timestamps with each log entry. Here’s how you can modify the previous code to include timestamps:

$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$message = "[$timestamp] Script execution started."
Add-Content -Path $logFilePath -Value $message

In this updated code:

  • We use the Get-Date cmdlet to retrieve the current timestamp in the desired format and store it in the $timestamp variable.
  • The $message variable now includes the timestamp enclosed in square brackets, followed by the log message.

Step 5: Log Errors and Warnings

In addition to logging informational messages, it’s crucial to log errors and warnings that may occur during script execution. PowerShell provides the Write-Error and Write-Warning cmdlets for this purpose. Here’s an example of how to log an error:

try {
    # Some code that may throw an exception
    $result = Invoke-SomeOperation
}
catch {
    $errorMessage = "[$timestamp] Error: $($_.Exception.Message)"
    Add-Content -Path $logFilePath -Value $errorMessage
    Write-Error $_.Exception.Message
}

In this code snippet:

  • We wrap the code that may throw an exception inside a try block.
  • If an exception occurs, the catch block is executed.
  • We construct an $errorMessage that includes the timestamp and the exception message.
  • The Add-Content cmdlet is used to append the $errorMessage to the log file.
  • Finally, we use the Write-Error cmdlet to display the exception message in the PowerShell console.

Similarly, you can use the Write-Warning cmdlet to log warnings.

Here is the complete PowerShell script.

$logDirectory = "C:\Logs"
$logFileName = "Log_$($env:COMPUTERNAME)_$(Get-Date -Format 'yyyyMMdd').log"
$logFilePath = Join-Path -Path $logDirectory -ChildPath $logFileName
New-Item -Path $logDirectory -Name $logFileName -ItemType File -Force
$message = "Script execution started."
Add-Content -Path $logFilePath -Value $message
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$message = "[$timestamp] Script execution started."
Add-Content -Path $logFilePath -Value $message

You can also see the exact output in the screenshot below:

powershell create log file

Read Get the Last Modified Date of a File in PowerShell

PowerShell Log Levels

In the Write- PowerShell cmdlets, PowerShell provides various types of log levels like:

  • Write-Verbose
  • Write-Debug
  • Write-Information
  • Write-Warning
  • Write-Error

Create a log file with date using PowerShell

Now, let us see how to create a log file with the date in PowerShell. Basically, it will create the file with the file name as of today’s date.

The script will check if any file exists with name as today’s date, if the file exists, then it will delete will first delete the file, else it will create the file and write the log message into it.

$todaysdate=Get-Date -Format "MM-dd-yyyy"

$logfilepath = "D:\"+$todaysdate+".log"

function WriteToLogFile ($message)
{
   Add-content $logfilepath -value $message
}
if(Test-Path $logfilepath)
{
    Remove-Item $logfilepath
}

WriteToLogFile "PowerShell log file message"
WriteToLogFile "This is another message"
WriteToLogFile "This is another another message"

This is how we can create log file with date in PowerShell.

This is how we can create a daily log file in PowerShell that will be created today.

Create a log file with datetime using PowerShell

Now, we can see how to create a log file with datetime using PowerShell.

We need to format the Get-Date PowerShell cmdlet to get the current date and time like below:

$todaysdate=Get-Date -Format "MM-dd-yyyy-hh-mm"

$logfilepath = "D:\"+$todaysdate+".log"

function WriteToLogFile ($message)
{
   Add-content $logfilepath -value $message
}
if(Test-Path $logfilepath)
{
    Remove-Item $logfilepath
}

WriteToLogFile "PowerShell log file message"

In the above example, the PowerShell log file will be created on the name as today’s date and time.

Create a log file if not exists in PowerShell

Now, let us see how to create a log file if not exists in PowerShell.

We can use the Test-Path PowerShell cmdlet to check if the file exists in the path or not.

We can also use New-Item PowerShell cmdlets to create a file in the folder path.

$todaysdate=Get-Date -Format "MM-dd-yyyy"
$folderpath="D:\"
$filename = $todaysdate+".log"

if (!(Test-Path $logfilepath))
{
New-Item -itemType File -Path $folderpath -Name $filename
}

You can see the output below:

PowerShell create log file if not exists
PowerShell create log file if not exists

This is how we can create a log file if not exists in PowerShell.

Create a log file with headers using PowerShell

Now, let us see how to create a log file with headers in PowerShell. Here, we will create a .csv file and add headers to it.

$filename = "Log-"+ (Get-Date -Format "MM-dd-yyyy")
$outfile = "D:\"+$filename+".csv"

$newcsv = {} | Select "DateAndTime","Message" | Export-Csv $outfile

$csvfile = Import-Csv $outfile
$csvfile.DateAndTime = Get-Date -Format "MM-dd-yyyy-hh-mm"
$csvfile.Message = "This is a test message"

$csvfile | Export-CSV $outfile

The above PowerShell script will create a .csv file and then it will add two headers (DateAndTime and Message). We will add a test log message also.

Create an error log file in PowerShell

Now, we will see how to create an error log file in PowerShell. Basically, we will use the try-catch statement, and in the catch statement, we will log the error message in a log file in PowerShell.

$filename = "Log-"+ (Get-Date -Format "MM-dd-yyyy")
$logfile = "D:\"+$filename+".log"

try
{
1/0
}
catch
{
$_.Exception.Message | Out-File $logfile
}

In the above PowerShell script, whenever an error will appear in the try statement, then the message will be logged in the catch statement in the PowerShell error log file.

Create a CSV Log File using PowerShell

In the same way we are creating .txt or .log file, we can also create .csv file in PowerShell to log information.

Now, let us see how to create a .csv log file in PowerShell.

To create a .csv file, we just need to change the file extension to .csv.

$todaysdate=Get-Date -Format "MM-dd-yyyy"

$logfilepath = "D:\"+$todaysdate+".csv"

function WriteToLogFile ($message)
{
   Add-content $logfilepath -value $message
}
if(Test-Path $logfilepath)
{
    Remove-Item $logfilepath
}

WriteToLogFile "PowerShell log file message"

This is how we can create csv log file in PowerShell.

Create a simple log file using PowerShell

Now, let us see how to create a simple log file in PowerShell. The PowerShell script will create a very simple log file and will log a text message. The file will be created on today’s date.

$filename = "Log- "+ (Get-Date -Format "MM-dd-yyyy")
$logfilepath = "C:\"+$filename+".log"
New-Item -Path $logfilepath  -ItemType file
Add-Content -Path $logfilepath -Value "This is a text file message"

In this PowerShell tutorial, we learned how to create a log file in PowerShell and the following things:

  • PowerShell create log file
  • PowerShell create log file with date
  • PowerShell log file with date and time

You may also like:

  • Hai Bijay, how can I create a logfile when I have a simple script which moves files from one directory to another?

  • Very valuable site , i have learned a lot. I have spotted one error. ” PowerShell create log file if not exists” , The parameter $logfilepath , is not declared and is not given a value.
    For the rest is is excellent , try and learn material.

  • >