Skip to content

Write to a text file using Powershell

03/06/2016

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.

Advertisements

From → Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: