davidst98
asked on
PowerShell Write to Screen in Color and Log FIle
Hi,
How can I write a message to the screen WITH color and also to a log file? Is there a simple line of code in PowerShell to do this? I found some examples online but it didn't allow me to change the font color on the screen.
David
How can I write a message to the screen WITH color and also to a log file? Is there a simple line of code in PowerShell to do this? I found some examples online but it didn't allow me to change the font color on the screen.
David
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The way I do it is with two lines.
$logfile = "X:\log.txt"
Write-host -f color "Stuff to go to the console"
write "stuff to go to log" | out-file -append $logfile
Maybe not the most elegant, but it works. It also allows me to include different information in the log than on the console. In an interactive script, you may want to be more verbose, but only want the log to contain a record of specific actions.
I usually write my scripts entirely with write-host while developing and then go through after they're complete to determine what I want to log with write statements.
$logfile = "X:\log.txt"
Write-host -f color "Stuff to go to the console"
write "stuff to go to log" | out-file -append $logfile
Maybe not the most elegant, but it works. It also allows me to include different information in the log than on the console. In an interactive script, you may want to be more verbose, but only want the log to contain a record of specific actions.
I usually write my scripts entirely with write-host while developing and then go through after they're complete to determine what I want to log with write statements.
If you need to be able to append, you could use
"some text" | Add-Content -path output2.txt -PassThru | Write-Host -ForegroundColor Yellow
More often I would say that the on-screen output differs from that sent to file, in which case you'll just need to use separate commands to write to a file and to output to console (meaningless example below).1..3 | % {
Write-Host "Processing $_" -foregroundcolor yellow
Add-Content -value "Number is $_" -path output.txt
}
ASKER