While looking for a method to generate some logging in a Powershell script to aid debugging I came across several suggestions…

#Method 01 - appends contents
$LogFile ="C:\PsTools\Method01.log"
$DateTime = Get-Date
Write-Output $DateTime "Performing some operation" | Add-Content $LogFile
#Method 02 - appends contents
Add-Content "C:\PsTools\Method02.log" "Performing some operation"
#Method 03 - overwrites existing contents
Write-Output "Performing some operation" | Out-File -FilePath "C:\PsTools\Method03.log" #optionally applying -Append will ensure existing file contents are retained
#Method 04 - overwrites existing contents
Write-Output "Performing some operation" | Set-Content "C:\PsTools\Method04.log"

I have opted to use the first method but appreciate that each method may be more suitable to a particular situation, it always pays to have more than one way to solve a problem!
If you have any further examples of writing to a text file then please feel free to leave a comment below.

1 thought on “Write to a text file using Powershell

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.