Windows OS Hub
  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux
  • Home
  • About

Windows OS Hub

  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux

 Windows OS Hub / PowerShell / Writing Output to Log Files in PowerShell Script

March 3, 2025

Writing Output to Log Files in PowerShell Script

Logging to simple text files is a convenient way to track all actions performed by a PowerShell script.  Such a log file is useful for debugging script errors and reviewing executed actions. In this article, we’ll explore different ways to log the output of PowerShell scripts by writing to text log files.

Contents:
  • Redirecting PowerShell Terminal Output to a Log File
  • Adding a Logging Function to a PowerShell Script
  • Automatic PowerShell Logging with Start-Transcript

Redirecting PowerShell Terminal Output to a Log File

By default, PowerShell command results are displayed in the console. To redirect the output of a PowerShell command to a text file, use one of the following methods:

  • Redirection using >> operator
  • Use Add-Content to add some plain text to the end of the log file
  • Use Out-File to write formatted text to a file

Here are examples of three different commands that add a new line with the output of a PowerShell command to the log file.

Write-Output "Files are successfully created in $env:computername" >> C:\PS\Logs\TestLog.txt
Add-Content -Path C:\PS\Logs\TestLog.txt -Value "Files are successfully created in $env:computername"
"Files are successfully created in $env:computername" | Out-File -FilePath C:\PS\Logs\TestLog.txt –Append
# The -Append parameter is used to add data to a file without overwriting existing data.

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 contents of the log file each time, use the Set-Content cmdlet.

Log PowerShell output to a text file

The main disadvantages of using such logging commands:

  • The current timestamp of when the event occurred is not logged
  • Every time you want to write something to the log, you have to call a somewhat complex PowerShell construct
  • The path to the log file is hardcoded

Adding a Logging Function to a PowerShell Script

If you prefer a more convenient logging method, the easiest way is to add a separate function to the PowerShell script that writes the data that it receives to a log file with a timestamp.

You can create a function as shown below:
$Logfile = "C:\PS\Logs\$($env:computername)posh.log"
function WriteLog
{
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $LogFile -value $LogMessage -Encoding UTF8
}

  • $Logfile – set the path to the log file (the folder must exist).
  • $($env:computername)posh.log – adds the computer name (hostname) to the log file name
  • $Stamp – Get the current date and format it according to the timestamp template

Now, call the WriteLog function when you want to log something to a text file.

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

Now, the log file contains the timestamp when the new line (log entry) was added.

powershell create log file with timestamp

Now, you can replace the console output via Write-Host command in all PS1 scripts with WriteLog.

To see the new log entries on the screen in real time, use the PowerShell command:

Get-Content -Tail 10 -Wait "C:\PS\Logs\$($env:computername)posh.log"

Automatic PowerShell Logging with Start-Transcript

PowerShell has another built-in transcript feature that writes all the commands that run in the console and their results to a text log file. To start recording commands in the current PowerShell session, run the command:

Start-Transcript

This will create a text log file in the Documents directory of the current user’s profile (the filename is specified in the console).

Transcript started, output file is C:\Users\user\Documents\PowerShell_transcript.DESKTOP-P2FHTKQ.+IzDgZiN.20210908163729.txt
You can change the default path to the transcript log file as follows:

Start-Transcript -Append C:\PS\Logs\PSScriptLog.txt

The -Append parameter specifies that new log entries should be appended to the end of the log file (without overwriting the existing data).

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

Write-Host "Transcript logging"
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:

Stop-Transcript

Then, open the transcript log file.

PowerShell_transcript log file - record a session to a text file

This text log contains the complete history of the PowerShell commands that were executed, along with any results output to the console.

This transcript log file also includes all errors and warnings, which can be very helpful when debugging complex PowerShell scripts.

The Start-Transcript and Stop-Transcript commands can be used in PowerShell scripts to natively log all actions and results.

The “Turn on PowerShell Transcription” GPO option (Computer Configuration –> Administrative Templates –> Windows Components –> Windows PowerShell) enables the automatic logging of all PowerShell commands and their output on the computer. After updating the GPO settings on the computer, a separate text log file will be created for each running powershell.exe (pwsh.exe) process, and all PowerShell commands and their outputs will be logged.

GPO option: Turn on PowerShell Transcription

You can also enable the transcription (logging) of all PowerShell commands and scripts through the registry (UNC path to shared network log directory can also be specified).

For Windows PowerShell commands:
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription" /v "EnableTranscripting" /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription" /v "EnableInvocationHeader" /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\Transcription" /v "OutputDirectory" /t REG_SZ /d C:\PS\LOGS /f

For new PowerShell Core:
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShellCore\Transcription" /v "EnableTranscripting" /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShellCore\Transcription" /v "EnableInvocationHeader" /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShellCore\Transcription" /v "OutputDirectory" /t REG_SZ /d C:\PS\LOGS /f

2 comments
9
Facebook Twitter Google + Pinterest
PowerShellWindows 11Windows Server 2022
previous post
How to Hide Users and Groups from the Global Address List on Exchange/Office 365
next post
Enable Group Policy Editor (gpedit.msc) on Windows 10/11 Home Edition

Related Reading

PowerShell: Get Folder Size on Windows

April 2, 2024

How to Download Offline Installer (APPX/MSIX) for Microsoft...

March 12, 2024

Install and Manage Windows Updates with PowerShell (PSWindowsUpdate)

March 17, 2024

How to Refresh (Update) Group Policy Settings on...

August 13, 2024

Start Menu or Taskbar Search Not Working in...

April 22, 2025

How to Backup and Restore Websites and IIS...

June 8, 2023

How to Run a Scheduled Task After Another...

June 8, 2023

Slow Access to Shared Folders and Network Drives...

March 11, 2024

2 comments

Jeff Lorenzen February 11, 2022 - 4:13 pm

Watch out for the invalid characters on this site. Those darn curly quotes get me every tiime!

Reply
bankey March 16, 2022 - 12:26 am

this will do that trick: just replace the first 0x0027 to the correct character 😉 took me a bit 🙂
-replace $([char]0x0027),$([char]0x0022)

Reply

Leave a Comment Cancel Reply

join us telegram channel https://t.me/woshub
Join WindowsHub Telegram channel to get the latest updates!

Recent Posts

  • Map a Network Drive over SSH (SSHFS) in Windows

    May 13, 2025
  • Configure NTP Time Source for Active Directory Domain

    May 6, 2025
  • Cannot Install Network Adapter Drivers on Windows Server

    April 29, 2025
  • Change BIOS from Legacy to UEFI without Reinstalling Windows

    April 21, 2025
  • How to Prefer IPv4 over IPv6 in Windows Networks

    April 9, 2025
  • Load Drivers from WinPE or Recovery CMD

    March 26, 2025
  • How to Block Common (Weak) Passwords in Active Directory

    March 25, 2025
  • Fix: The referenced assembly could not be found error (0x80073701) on Windows

    March 17, 2025
  • Exclude a Specific User or Computer from Group Policy

    March 12, 2025
  • AD Domain Join: Computer Account Re-use Blocked

    March 11, 2025

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Install and Manage Windows Updates with PowerShell (PSWindowsUpdate)
  • How to Download Offline Installer (APPX/MSIX) for Microsoft Store App
  • Configuring Port Forwarding in Windows
  • Start Menu or Taskbar Search Not Working in Windows 10/11
  • Get-ADUser: Find Active Directory User Info with PowerShell
  • Adding Drivers into VMWare ESXi Installation Image
  • Tracking and Analyzing Remote Desktop Connection Logs in Windows
Footer Logo

@2014 - 2024 - Windows OS Hub. All about operating systems for sysadmins


Back To Top