Last active
December 16, 2016 15:16
-
-
Save automationhaus/6d239d7510f7784757140f82242b3861 to your computer and use it in GitHub Desktop.
Write Output to the Screen and to File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Write-Tee | |
{ | |
<# | |
.SYNOPSIS | |
Write output to the screen and to file simultaneously | |
.DESCRIPTION | |
Simply write your screen output to a file with automatic coloring based with special sytax between square brackets. Enable debugging and produce debugging only ouptut. | |
.EXAMPLE | |
Write-Tee "[=] This is the first task in my loop" | |
.EXAMPLE | |
Write-Tee @" | |
Write a long message without a prefix and overwrite your log file | |
"@ -NoPrefix -Overwrite | |
.EXAMPLE | |
Write-Tee "[?] Collect info without a line break" -NoNewLine; Read-Host | |
.LINK | |
https://automation.haus/powershell-write-host-console-log-file | |
#> | |
[cmdletbinding()] | |
param | |
( | |
[Parameter(Position=0,ValueFromPipeline=$true)] | |
[string]$msg, | |
[string]$ForegroundColor = "White", | |
[string]$OutFile=$LogFile, | |
[switch]$Overwrite, | |
[switch]$NoNewLine, | |
[string]$Prefix=" - ", | |
[switch]$NoPrefix | |
) | |
$Info = "i"; $Task = "="; $Errors = "!"; $Inquiry = "?"; $Debugging = "d"; $Response = "r" | |
$DBG = $False | |
switch -regex ($msg) | |
{ | |
"\[$Info\]" { $ForegroundColor = "Yellow" } | |
"\[$Task\]" { $ForegroundColor = "Cyan"; $Prefix = " " } | |
"\[$Errors\]" { $ForegroundColor = "Red" } | |
"\[\$Inquiry\]" { $ForegroundColor = "Magenta" } | |
"\[$Debugging\]" { $ForegroundColor = "Magenta"; $DBG = $True } | |
"\[$Response\]" { if($ForegroundColor -eq "White"){ $ForegroundColor = "Green" } } | |
} | |
if(($DBG -eq $False) -or ($DBG -and $Debug)){ $Write = $True } | |
if(!$NoPrefix) | |
{ | |
if($Write){ Write-Host $Prefix -NoNewline } | |
} | |
if($NoNewLine) | |
{ | |
if($Write){ Write-Host -ForegroundColor $ForegroundColor $msg -NoNewline } | |
} | |
else | |
{ | |
if($Write){ Write-Host -ForegroundColor $ForegroundColor $msg } | |
} | |
if(!$NoPrefix -and $msg -ne ""){ $msg = $Prefix + $msg } | |
if($OutFile -ne "") | |
{ | |
if(!$Overwrite) | |
{ | |
if($NoNewLine) | |
{ | |
if($Write){ [System.IO.File]::AppendAllText($OutFile, $msg, [System.Text.Encoding]::Unicode) } | |
} | |
else | |
{ | |
if($Write){ $msg | Out-File $OutFile -Append } | |
} | |
} | |
else | |
{ | |
if($Write){ $msg | Out-File $OutFile -Force } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment