Created
December 14, 2022 17:44
-
-
Save shalomb/6258ed5d54aa3730cbb0c527ba46eef4 to your computer and use it in GitHub Desktop.
PowerShell Redefine Write-Host, Write-Output for Logging
This file contains hidden or 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
# PowerShell | |
Set-StrictMode -Version 2.0 | |
Set-PSDebug -Trace 0 | |
$ErrorActionPreference = 'STOP' | |
function Register-LogWriter { | |
<# | |
.SYNOPSIS | |
Create a new writer around the equivalent function under Microsoft.PowerShell.Utility | |
.EXAMPLE | |
Register-LogWriter -Function Write-Host | |
Write-Host "Message in a bottle" # Log timestamps automatically prepended | |
#> | |
[cmdletbinding()] param ( | |
[Parameter(Mandatory,ValueFromPipeline)] | |
$Function | |
) | |
$Code = { | |
[cmdletbinding()] param ( | |
[Parameter(Mandatory,ValueFromPipeline)] | |
$String | |
) | |
BEGIN { | |
$Hostname = [System.Net.Dns]::GetHostName() | |
} | |
PROCESS { | |
$TimeStamp = Get-Date -Format "yyyy-MM-ddTHH:MM:ss.ffff" | |
iex "Microsoft.PowerShell.Utility\$Function '$TimeStamp ${Hostname}: $string'" | |
} | |
}.GetNewClosure() | |
New-Item -Path function: -Name "script:$Function" -Value $Code -Force | Out-Null | |
} | |
Register-LogWriter -Function Write-Host | |
Register-LogWriter -Function Write-Output | |
Register-LogWriter -Function Write-Verbose | |
# Quick Tests | |
Write-Host "Host" | |
sleep 0.6 | |
Write-Output "Output" | |
sleep 0.6 | |
Write-Verbose "Verbose" -Verbose | |
sleep 0.6 | |
"oo" | |
"Host" | Write-Host | |
"Output" | Write-Output | |
"Verbose" | Write-Verbose -Verbose |
Author
shalomb
commented
Dec 14, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment