Q&D Verbose and Debug logging with private functions

If you’ve ever written a script with write-verbose and write-debug for interactive use, and then later wished you could write those events to a log file, here’s a quick way to add that without making a lot of changes to the existing code,

If you want to add each event to a log file immediately when it occurs:

$logfile = './logfile.log'

function private:Write-Debug {
  if ([int]$DebugPreference){
    Add-Content $args[0] $logfile
    write-debug $args[0]
    }
}

function private:Write-Verbose {
  if ([int]$VerbosePreference){
    Add-Content $args[0] $logfile
    write-verbose $args[0]
    }
}

If you want to accumulate them in a variable, so you can write them out at the end of the script:


$logvar = {}.invoke()

function private:write-Verbose {
 if ([int]$verbosepreference){
      $logvar.add($args[0])
      write-verbose $args[0]
      }
 } 
  
function private:write-Debug {
  if([int]$debugpreference){
    $logvar.add($args[0])
    write-Debug $args[0]
    }
}

Note: write-debug and write-verbose will take the output string as either an argument or from the pipeline. This only works if the code is using the strings as arguments.

One response to “Q&D Verbose and Debug logging with private functions

  1. Pingback: Verbose and Debug logging with private functions | psjjw

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s