Catalin
Posts: 6506
Joined: Wed Jun 13, 2018 7:49 am

How to add logging functionality to your PowerShell custom actions

Thu Nov 16, 2023 1:48 pm

Hello,

Today, we'll be discussing how to make your PowerShell custom actions log their output to a log file.

This involves modifying the custom action itself by adding the functions that will log, either a message or an error.

First of all, we will have to decide the log's location. For this, I will be using the %temp% location.

Code: Select all

$logFileLocation = $env:temp + "\CustomActionLog.txt"
Now, if this file does not already exist, we need to create it.

To do this, we can use the "test-path" cmdlet.

Code: Select all

if (-not(test-path $logFileLocation)){
new-item -itemtype File -path $logFileLocation
}
Now that we created the file, we can create our functions as well.

Code: Select all

function Log {
    param ([string]$Message)

    $timeStamp = Get-Date -Format "HH:mm:ss.fff"
    $outMessage = $timeStamp + ": " + $Message
    $outMessage | Out-File -FilePath $logFileLocation -Append -Encoding UTF8
}

Code: Select all

function LogError {
    param ([string]$Message)
    
	$ErrorMessage = "[Error] " + $Message
    Log($ErrorMessage)
}
By using the above two functions, you should be able to handle logging the results of your PowerShell custom actions in a log that is separate from the MSI log.

Hope you'll find this useful. :)

Best regards,
Catalin
Catalin Gheorghe - Advanced Installer Team
Follow us: Twitter - Facebook - YouTube

Return to “Sample Projects”