I needed a way to log the console output in PowerShell, which would then allow me to email this (a quick and easy way for me to check that my automated scripts were working correctly).
The following function does just that, sort of.
1 2 3 4 5 6 7 8 9 10 11 |
# Log function. $Log = $null Function Log($a) { If (-Not ($Log -eq $null)) { $global:Log += "`r`n" } $global:Log += $a Return($a) } |
Instead of capturing everything that is written to the console, text is passed to the Log function which then updates the $Log string before returning the same text to ensure it is written to the console.
Line breaks are automatically added to the string.
The code below shows how to use the Log function.
1 |
Log("hello world!") |
It’s important to remember that this function will not capture any errors thrown by your script. So, you’ll need to make sure you handle errors correctly.