Skip to content

Instantly share code, notes, and snippets.

@shalomb
Created December 14, 2022 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shalomb/6258ed5d54aa3730cbb0c527ba46eef4 to your computer and use it in GitHub Desktop.
Save shalomb/6258ed5d54aa3730cbb0c527ba46eef4 to your computer and use it in GitHub Desktop.
PowerShell Redefine Write-Host, Write-Output for Logging
# 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
@shalomb
Copy link
Author

shalomb commented Dec 14, 2022

.\logwriter.ps1
2022-12-14T18:12:39.2888 VM3890715E: Host
2022-12-14T18:12:39.9112 VM3890715E: Output
VERBOSE: 2022-12-14T18:12:40.5280 VM3890715E: Verbose
oo
2022-12-14T18:12:41.1538 VM3890715E: Host
2022-12-14T18:12:41.1708 VM3890715E: Output
VERBOSE: 2022-12-14T18:12:41.1802 VM3890715E: Verbose

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment