Writing Output to Log Files in PowerShell Script

You can use simple text log files to control running and track all of the activities in your PowerShell scripts. This is useful when debugging errors or auditing script actions. In this article, we’ll show some ways to use logging in PowerShell scripts by writing output to text log files.

In the simplest case, if you want to write the output of an information message or a PowerShell command result to a text log file, you can use one of the following formats to redirect the PS output to a text file:

Write-Output "Files are successfully created in $env:computername" >> C:PSLogsTestLog.txt
Add-Content -Path C:PSLogsTestLog.txt -Value "Files are successfully created in $env:computername"
"Files are successfully created in $env:computername" | Out-File -FilePath C:PSLogsTestLog.txt –Append

In all cases, the commands add a new line to a txt file with the text you have specified.

If you want to overwrite the log file contents each time, use the Set-Content cmdlet.

The main drawback of this method is that you cannot figure out when an entry was written to the log (an event occurred). You can add the current timestamp to the log file. It will help to identify the time when the script was run and a specific event occurred.

To make it more convenient, you can create a separate function in your PowerShell script that will write the data it receives to a log file and add the timestamp for each event.

You can create a function as shown below:

$Logfile = "C:PSLogsproc_$env:computername.log"
function WriteLog
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $LogFile -value $LogMessage

Then call the WriteLog function if you want to log something.

WriteLog "The script is run”
WriteLog "Calculating…."
Start-Sleep 20
WriteLog "The script is successfully executed"

Now you can see the time of each entry in the log file.

You can replace Write-Host calls with LogWrite ones in your script.

PowerShell has a built-in transcript feature to save all commands and outputs shown in the PS console to a text log file.

To log your current PowerShell session, the Start-Transcript cmdlet is used.

After running the command, a message appears showing the file the output of all commands is logged to. By default, the log file is located in the current user profile:

Transcript started, output file is C:UsersuserDocumentsPowerShell_transcript.DESKTOP-P2FHTKQ.+IzDgZiN.20210908163729.txt

You can specify the path to the text file as follows:

Start-Transcript -Append C:PSLogsPSScriptLog.txt

The –Append option indicates that new sessions will be logged to the end of the file (without overwriting it).

Run some PowerShell commands that output the results to the console. For example, let’s display a list of running processes, services, and the AD replication status:

Get-Process| where-object {$_.WorkingSet -GT 500000*1024}|select processname,@{l="Used RAM(MB)"; e={$_.workingset / 1mb}} |sort "Used RAM(MB)" –Descending
Get-Service | Where-Object {$_.status -eq 'Running'}
Get-ADReplicationFailure -Target mun-dc01

Stop logging for the current PowerShell session:


Then open the transcript log file.

As you can see, the log shows the entire history of the PowerShell commands that were run in the console and all the output.

All errors and warnings are also logged, and it is extremely convenient when debugging complex PowerShell scripts.

You can use Start-Transcript and Stop-Transcript cmdlets in your PowerShell scripts to natively log all actions and outputs. Using the Group Policy option Turn on PowerShell Transcription (Computer Configuration –> Administrative Templates –> Windows Components –> Windows PowerShell), you can enable automatic logging of all run PowerShell commands and output on a computer. After updating GPO settings on the computer, a separate text log file will be created for each running powershell.exe process and all PS commands and their outputs will be logged.

About Seyi

Check Also

The computer restarted unexpectedly or encountered an unexpected loop error on Windows 10/11

In some cases, during a clean Windows installation, upgrading to a new Windows 11, installing …

Leave a Reply

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