I have a powershell script and I want to write to a console and write to a log file with one call.
I was doing this...
Start-Transcript -Path $TargetDir\Log.log
Write-Host "Stuff"
... which works great, except that the newlines it generates are LF, which means my logs look great in every text editor on earth, except for notepad.
Here's what I have for this...
function global:Write-Notepad
(
[string] $Message,
[string] $ForegroundColor = 'Gray'
)
{
Write-Host "$Message`r" -ForegroundColor $ForegroundColor
}
...which writes a CR to the end of every message, but it doesn't seem to write out lines like this...
&$ACommand | Write-Notepad
I'm not sure what syntax the piping operator expects, but I would greatly appreciate help.
PowerShell has a built-in transcript feature to save all commands and outputs shown in the PS console to a text log file. To log your current PowerShell session, the Start-Transcript cmdlet is used. The –Append option indicates that new sessions will be logged to the end of the file (without overwriting it).
Writes the specified objects to the pipeline. If Write-Output is the last command in the pipeline, the objects are displayed in the console.
In PowerShell multiline command can be easily created using ` (backtick character) to split long or a single line command into multiline statements. Backtick (`) character is used as an escape character, it basically escapes the newline character and results in line continuation.
The PowerShell way uses a single cmdlet called Set-content. This cmdlet allows us to much more easily use PowerShell to write to a file. This PowerShell cmdlet is a built-in cmdlet that has one purpose; to write to a file.
Try this:
& $ACommand | Tee-Object -FilePath $TargetDir\Log.log | Write-Host
Tee-Object will send a copy of the pipeline objects to a file or a variable, and output at the same time.
Here's the solution I settled on...
# This method adds a CR character before the newline that Write-Host generates.
# This is necesary, because notepad is the only text editor in the world that
# doesn't recognize LF newlines, but needs CR LF newlines.
function global:Write-Notepad
(
[string] $Message,
[string] $ForegroundColor = 'Gray'
)
{
Process
{
if($_){ Write-Host "$_`r" }
}
End
{
if($Message){ Write-Host "$Message`r" -ForegroundColor $ForegroundColor }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With