{"id":278,"date":"2021-03-28T15:08:23","date_gmt":"2021-03-28T14:08:23","guid":{"rendered":"http:\/\/192.168.8.14\/?p=278"},"modified":"2021-03-28T15:08:23","modified_gmt":"2021-03-28T14:08:23","slug":"write-to-debug-log-file-function","status":"publish","type":"post","link":"https:\/\/www.jasonstreet.com\/?p=278","title":{"rendered":"Write to debug\/log file function"},"content":{"rendered":"\n<p>Here is a function to save time when writing logging or debugging information in scripts. It has grown from a simple &#8220;dump stuff to a file&#8221; to a handy &#8220;Swiss army knife&#8221; of logging. The function is not perfect and will no doubt keep growing.<\/p>\n\n\n\n<p>A quick thing to mention is that if the file locations are not passed to the function it will default to the variables $DebugFile and $LogFile. So if you define those at the start of your main script you will save yourself a lot of typing.<\/p>\n\n\n\n<p><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: powershell; title: ; notranslate\" title=\"\">\n&lt;# \n  .SYNOPSIS\n     Log to debug log file and\/or log file.\n\n  .DESCRIPTION\n     writes a message\/or object to a debug file. Can also write to the screen and log file. \n     Can also pause or exit on an error\n     message will have the format of\n     OK    message here\n     fail  message here\n\n\n  .PARAMETER message \n    The message to be displayed in the debug\/log file or on screen\n\n  .PARAMETER NewDebugFile \n    the path to the debug file\n\n\n  .PARAMETER NewLogFile \n    the path to the log file\n\n  .PARAMETER ScreenOut\n    Set to also out put to the screen (Green OK, red Fail)\n\n  .PARAMETER ReturnCode \n    used to get the stats of the last commend $? or $true - success, $false - failed\n\n  .PARAMETER IgnoreReturnCode \n    if the return code is not null, setting this will ignore it.\n\n  .PARAMETER ClearDebugFile \n    will write the time to the debug file with no append, clearing the file.\n\n  .PARAMETER ClearLogFile \n    will write the time to the log file with no append, clearing the file.\n\n  .PARAMETER Logit \n    Will write the same message to the log file as well as the debug file.\n\n  .PARAMETER PauseOnError \n    Will pause execution if the ReturnCode is false, and wait for the user to press enter.\n\n  .PARAMETER StopOnError \n    Will exit execution if the ReturnCode is false.\n\n  .EXAMPLE\n    Send-Debug -Message &quot;the command run&quot; -ReturnCode $? -NewDebugFile &quot;.\\debug.log&quot;\n    &quot;OK    the command run&quot; is appended to the file debug.log (if the previous command was successfull)\n    &quot;Fail  the command run&quot; is appended to the file debug.log (if the previous command failed)\n\n  .EXAMPLE\n    Send-Debug -Message &quot;the command run&quot; -NewDebugFile &quot;.\\debug.log&quot;\n    &quot;      the command run&quot; is appended to the file debug.log \n\n  .EXAMPLE\n    Send-Debug -Message &quot;the command run&quot; -ReturnCode $? -NewDebugFile &quot;.\\debug.log&quot; -ClearDebugFile\n    &quot;run at date time&quot;\n    &quot;      the command run&quot; is appended to the file debug.log \n\n  .EXAMPLE\n    Send-Debug -Message &quot;the command run&quot; -ReturnCode $? -NewDebugFile &quot;.\\debug.log&quot; -NewLogFile &quot;.\\Log.log&quot; -Logit\n    &quot;OK    the command run&quot; is appended to the file debug.log and log.log (if the previous command was successful)\n    &quot;Fail  the command run&quot; is appended to the file debug.log and log.log (if the previous command failed)\n#&gt;\nfunction Send-Debug\n{\n    &#x5B;CmdletBinding()]\n    param\n    (\n        &#x5B;Parameter(Mandatory = $false)]  $NewDebugFile = $DebugFile, \n        &#x5B;Parameter(Mandatory = $false)]  $NewLogFile = $LogFile,        \n        &#x5B;Parameter(Mandatory = $false,ValueFromPipeline=$true)] $Message = &quot; &quot;,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$ScreenOut = $false,\n        &#x5B;Parameter(Mandatory = $false)] $ReturnCode = $null,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$IgnoreReturnCode = $false,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$ClearDebugFile = $false,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$ClearLogFile = $false,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$Logit = $false,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$PauseOnError = $false,\n        &#x5B;Parameter(Mandatory = $false)] &#x5B;switch]$StopOnError = $false\n    )\n\n    if($Message -eq $null){$Message = &quot; &quot;} # $Message should not ever be null but bad things happen if it is.\n\n    # look for the $ClearDebugFile or $ClearLogFile settings and dont use the appand setting when writing to files. \n    if($ClearDebugFile) {(&quot;Run at &quot; + (get-date).tostring()) | out-file $NewDebugFile}\n    if($ClearLogFile)   {(&quot;Run at &quot; + (get-date).tostring()) | out-file $LogFile}\n\n    # if there is no return code or the $IgnoreReturnCode setting is set.\n    if ($ReturnCode -eq $null -or $IgnoreReturnCode -eq $true)\n    {\n        # if $Message is an object, dont put the leading spaces in, just dump the object to file\n        if ($Message.gettype().name -match &quot;object&quot;)\n        {\n            $LogMessage = $Message\n        }else{\n            $LogMessage = &quot;    &quot; + $Message\n        }\n        \n        # if the $ScreenOut setting is set we also use write-host to output to the screen\n        if ($ScreenOut){write-host $LogMessage -ForegroundColor yellow}\n\n        # if the $Logit setting is set we also use  output to the $NewLogFile\n        if ($Logit)    {$LogMessage  | out-file $LogFile -Append}\n\n        # now we just dump $LogMessage to the debugFile\n        $LogMessage | out-file $NewDebugFile -Append \n    }\n\n    # if there is a successful return code AND the $IgnoreReturnCode setting is not set.\n    if ($ReturnCode -eq $true -and $IgnoreReturnCode -eq $false)\n    {\n        if ($Message.gettype().name -match &quot;object&quot;)\n        {\n            $LogMessage = $Message\n        }else{\n            $LogMessage = &quot;OK  &quot; + $Message\n        }\n\n        # if the $ScreenOut setting is set we also use write-host to output to the screen, this section outputs green text\n        if ($ScreenOut){write-host $LogMessage -ForegroundColor Green}\n        if ($Logit)    {$LogMessage  | out-file $LogFile -Append}\n        $LogMessage | out-file $NewDebugFile -Append\n    }\n\n    # if there is a failure return code AND the $IgnoreReturnCode setting is not set.\n    if ($ReturnCode -eq $false -and $IgnoreReturnCode -eq $false)\n    {\n        if ($Message.gettype().name -match &quot;object&quot;)\n        {\n            $LogMessage = $Message\n        }else{\n            $LogMessage = &quot;Fail &quot; + $Message\n        }\n\n        # if the $ScreenOut setting is set we also use write-host to output to the screen, this section outputs red text\n        if ($ScreenOut){write-host $LogMessage -ForegroundColor red}\n        if ($Logit)    {$LogMessage  | out-file $LogFile -Append}\n        $LogMessage | out-file $NewDebugFile -Append\n    }\n\n    if ($PauseOnError -and ($ReturnCode -eq $false))\n    {\n        Write-host &quot;An error has occured, Press Enter to continue&quot; -ForegroundColor Red\n        $bob = read-host &quot;Press Enter to continue&quot;\n    }\n\n    if ($StopOnError -and ($ReturnCode -eq $false))\n    {\n        Write-host &quot;An error has occured, unable to continue&quot; -ForegroundColor Red\n        exit\n    }\n}\n<\/pre><\/div>\n\n\n<p>So here is how it works:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nset-something -SomethingTo 5\nSend-Debug -Message &quot;set something to 5&quot; -ReturnCode $? -NewDebugFile &quot;.\\Debug.log&quot;\n<\/pre><\/div>\n\n\n<p>The Send-Debug function will append the line &#8220;set something to 5&#8221; to the log file if the set-something was successful. If not it will append &#8220;Fail   set something to 5&#8221;.<\/p>\n\n\n\n<p>To much text? we can shorten that up a bit.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n$DebugFile = &quot;.\\Debug.log&quot;\nset-something -SomethingTo 5\nSend-Debug -ReturnCode $? -Message &quot;set something to 5&quot;\n<\/pre><\/div>\n\n\n<p>And then expand on that&#8230;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n$DebugFile = &quot;.\\Debug.log&quot;\nset-something -SomethingTo 5\nSend-Debug -ReturnCode $? -Message &quot;set something to 5&quot; -ScreenOut -ClearDebugFile\n<\/pre><\/div>\n\n\n<p>The above will also write the output to the screen in green if successful or red if not. Will also clear the Debug file, best to use this at the first call so you create\/clear the debug file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n$DebugFile = &quot;.\\Debug.log&quot;\n$LogFile = &quot;.\\LogFile.log&quot;\nset-something -SomethingTo 5\nSend-Debug -ReturnCode $? -Message &quot;set something to 5&quot; -ScreenOut -Logit -PauseOnError\n<\/pre><\/div>\n\n\n<p>Now this will output to the screen in the same way as the last example. But will also log to a log file. This is handy for a log file slowing a higher level summery then a full debug log. Finally the function will pause if the set-something command failed.<\/p>\n\n\n\n<p>Or if you need to log the contents of unknown objects&#8230;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n$DebugFile = &quot;.\\Debug.log&quot;\n$LogFile = &quot;.\\LogFile.log&quot;\nset-something -SomethingTo 5 | Send-Debug -ReturnCode $? -ScreenOut -Logit\n<\/pre><\/div>\n\n\n<p>The result of the command set-something -SomethingTo 5 will be piped in to Send-Debug as the message. If that input is an object it will be written to the debug file and printed to the screen.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here is a function to save time when writing logging or debugging information in scripts. It has grown from a simple &#8220;dump stuff to a file&#8221; to a handy &#8220;Swiss army knife&#8221; of logging. The function is not perfect and will no doubt keep growing. A quick thing to mention is that if the file&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[4],"tags":[56,17,55,13],"class_list":["post-278","post","type-post","status-publish","format-standard","hentry","category-powershell","tag-debugging","tag-function","tag-logging","tag-powershell"],"_links":{"self":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts\/278","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=278"}],"version-history":[{"count":7,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts\/278\/revisions"}],"predecessor-version":[{"id":672,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=\/wp\/v2\/posts\/278\/revisions\/672"}],"wp:attachment":[{"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=278"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=278"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jasonstreet.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=278"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}