PowerShell Log function with word wrapped output to the screen

I like to have logging in most scripts I write, and this is the current incarnation of my logging function. It logs to c:\location\of\script.ps1.log (or wherever/whatever your script is named). It uses write-host to output a word wrapped version of the text to the screen. It reads in the window size to determine the best place to cut up the sentence.

# Name of the currently executing script
$ScriptName = $MyInvocation.MyCommand.Path 
# Simple log file name, OurScriptName.ps1.log
$LogFile = $ScriptName + ".log"
# Word wrap function, return word wrapped version of passed string
function WordWrapStr($str)
	# Holds the final version of $str with newlines
	$strWithNewLines = ""
	# current line, never contains more than screen width
	$curLine = ""
	# Loop over the words and write a line out just short of window size
	foreach ($word in $str.Split(" "))
		# Lets see if adding a word makes our string longer then window width
		$checkLinePlusWord = $curLine + " " + $word
		if ($checkLinePlusWord.length -gt (get-host).ui.rawui.windowsize.width)
			# With the new word we've gone over width
			# append newline before we append new word
			$strWithNewLines += [Environment]::Newline
			# Reset current line
			$curLine = ""
		# Append word to current line and final str
		$curLine += $word + " "
		$strWithNewLines += $word + " "
	# return our word wrapped string
	return $strWithNewLines
# Log function, append passed string to log file
function Log([string]$logline)
    $timestamp = Get-Date -f "yyyy-MM-dd HH:mm:ss"
    $StdLogLine = "$timestamp> $logline"
	# Add the log line to our log file in ascii with timestamp
    Add-Content $LogFile $StdLogLine -encoding ascii
    # Print to the screen the word wrapped version (no timestamp)
	write-host (WordWrapStr $logline)
Log "This text will first be appended to $LogFile, ascii encoded.  Also cut up the text and print it out word wrapped to the screen.  It works even with really long lines."

Example with and without word wrapped write-host:

This entry was posted in General and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *