Powershell Write-Host append to text file – computer name and time stamp


I am a Powershell noobie and I am currently writing my second script so bear with me. I am trying to do a write-host and output my write-host message along with a time stamp and what computer is completing my various script blocks to a text file and I am having issues with which syntax to make things work.

I tried the following for testing purposes. This will be going to a server once I get the Syntax down – for now it goes to my local C: drive.

write-host "folders created successfully $env:computername" >> c:\scripts\testlog.txt

The behavior I'm seeing is the text file is being created but there's no contents in it – all blank.

Best Answer

Write-Host does not use standard out. It always outputs to the console directly, skipping anything else. Write-Output does output to standard out.

To do answer your specific question -- how to append the output of a command to a text file -- you could use:

Write-Output "folders created successfully $env:computername" >> C:\scripts\testlog.txt

However, you could also use Add-Content:

Add-Content -Path C:\scripts\testlog.txt -Value "folders created successfully $env:computername"

Or you can pipe to Out-File -Append:

"folders created successfully $env:computername" | Out-File -FilePath C:\scripts\testlog.txt -Append

Why would you use different methods? They have a few differences which you won't run into very often. The redirection operators don't give you as much control over what happens (encoding, etc.).