Write-Log PowerShell Logging Function

The Write-Log PowerShell advanced function is designed to be a simple logger function for other cmdlets, advanced functions, and scripts. Often when running scripts one needs to keep a log of what happened and when. The Write-Log accepts a string and a path to a log file and ap

4.4 Star
10,817 times
Add to favorites
E-mail Twitter del.icio.us Digg Facebook
  • Is this the correct implementation
    2 Posts | Last post February 07, 2020
    • PKK
      This is a good script that i am using, but it appears that the error is only shown in the console, i wanted it logged along with the Info, this is what i have
      * in my if statement, i have 2 things, Write-error and Write-Log where i am specifying the -level, that seems to work, but i thought that the Write-error should have been sufficient to log the error in the log (i am newby, seaching for scripts here and there to get a task done, if this is foolish, please forgive)
      Also, the Catch statement, what is this statement do and produce in return? Write-Log -Message $_.Exception.Message
      . D:\Data\BF_Scripts\Write-Log.ps1
      		Write-Log -Message 'Copying File from the Drop location to the Server...'
      		$sourceFilePath = "\\linkThatDoesntExist\20191213_BFI_SAMPLE_DATA_c.csv"
      			# file with path $sourceFilePath doesn't exist
      		  Write-error " $sourceFilePath doesn't exist, Unable to copy file" 
                  Write-Log -Message "$sourceFilePath doesn't exist, Unable to copy file" -Level Error
      			Copy-Item $sourceFilePath -Destination $filePath
      			Write-Log -Message 'File copied successfully!!'
      		Write-Log -Message $_.Exception.Message
    • The Write-Log function doesn't capture errors automatically. You could use Try/Catch to write the error. The latest version of this script is part of the MrAToolbox on the PowerShell gallery.
      so in your catch you should have
      Write-Log -Message $_.Exception.Message -Level Error
  • Logging Error throws exception
    3 Posts | Last post September 10, 2018
    • Hi,
      Thanks for this script. Its really helpful. 
      While it logs Warning and Info, during Error logging, it throws exception :
      VERBOSE: Log message 2
      WARNING: Log message 2
      Write-Log : Log message 2
      At C:\Users\Administrator\Downloads\Function-Write-Log.ps1:120 char:1
      + Write-Log -Level 'Error' -Message 'Log message 2' -Path 'C:\Amit.log'
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
          + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Write-Log
      I can not figure out why. Can you kindly tell me what could be possibly wrong here?
      Calling function as : Write-Log -Level 'Error' -Message 'Log message 2' -Path 'C:\Amit.log'
    • This looks like you may be running PowerShell without being elevated and you do not have permission to write to the c:\amit.log file. Try creating a c:\Logs directory and use that for your scripts. I think that might even be the default path.
    • Hi,
      One possible solution could be : 
      Change this:
      switch ($Level) { 
                  'Error' { 
                      Write-Error $Message 
                      $LevelText = 'ERROR:' 
                  'Warn' { 
                      Write-Warning $Message 
                      $LevelText = 'WARNING:' 
                  'Info' { 
                      Write-Verbose $Message 
                      $LevelText = 'INFO:' 
      To the below code:
      switch ($Level) { 
                  'Error' { 
                      Write-Verbose $Message 
                      $LevelText = 'ERROR:' 
                  'Warn' { 
                      Write-Warning $Message 
                      $LevelText = 'WARNING:' 
                  'Info' { 
                      Write-Verbose $Message 
                      $LevelText = 'INFO:' 
      Possibility of issue could be:
      Powershell in itself consider "write-error" as errorneous message for any error, therefore it may be performing in its own code style and not as we want in log file. But, "write-versbose" can achieve this thing and will give the required output without error/exception on console.
      Correct me, if my understanding is wrong :)
  • Errors and Warnings Only?
    3 Posts | Last post October 19, 2017
    • Thanks for the great function.  Is it possible to set only warnings and errors to write to the log and exclude info?
    • In a way yes. Since this function only writes a log entry when you call it, then just only call it for errors and warnings.
      For example:
      Write-Verbose 'Checking system'
      Write-Log -Message 'uh oh' -Level Error
    • I think Owen is asking about a 'log4j' like behavior where the log statements can stay in the code at the appropriate 'level' but the output is controlled by a global logging level. For example in dev I can set logging level to "Info" and see/log all Info, Warn and Error level messages; while in prod I set the logging level to "Warn" or "Error" and skip all the 'Info' level messages.
      I modified the Write-Log utility slightly to get this behavior. The changes are:
      1 Add a global logging level parameter
      2 at the top of the Process block
              # If the log level of the message is < logging level, do-nothing;
              # Default being Info, if LoggingLevel is set to Info, all Info, Warn and Errors get logged
              if (($LoggingLevel -eq "Warn" -and $Level -eq "Info") -or ($LoggingLevel -eq "Error" -and ($Level -eq "Info" -or $Level -eq "Warn")) ) {
      Through the PSDefaultParameterValues mechanism - we can set the global logging level from the calling script
      I am contemplating adding a 'Debug' level to the script to be the lowest loggable level. Thanks for contributing this tool.
  • propsal => add -width
    2 Posts | Last post April 13, 2017
    • Logfile content is being truncated. in my configuration the log file line length is set to 80 characters (by system default). to get rid of this limit, just add the -width parameter and set it to a value 1024 => like so: 
      "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append -Width 1024
    • Thank you for the feedback.
  • Verified on Windows 10
    1 Posts | Last post April 10, 2017
    • Just wanted to let others know that this does work on Windows 10. The description still says it hasn't been tested. 
  • I am really stumped
    2 Posts | Last post January 05, 2017
    • How the heck do I use this script?  I would like to add this to my existing scripts but cannot even figure out how to do it, where it logs too, etc.  Any help would be appreciated.
    • The script is a function so it must be loaded as part of a module or "dot sourced." (i.e. . .\Function-Write-Log.ps1). After it has been loaded into memory you can call the function Write-Log from within your scripts. 
      To save time you can install it via PowerShell 5.0 using Install-Module MrAADAdministration. This will install write-log as well as other user functions to your system. 
      Usage instructions are provided in the help.
      Write-Log -Message 'Log entry'
      The default location is in the script (i.e. c:\Logs\PowerShellLog.log), but you can change that with the Path parameter.
      Finally, read more at the blog post for this function http://mrautomaton.com/2015/11/30/psblogweek-building-readable-text-log-files/.
  • Full Error info not added to the log file
    1 Posts | Last post August 01, 2016
    • i have managed to get it to work. but the info into the log file only adds "2016-08-01 12:46:42  The object already exists." for example, it doesn't tell me which object exactly.
      I am busy testing this in a lab environment, example of what i need to have appear in the log as this will be send via another scripted email to the HR/Servicedesk to show whats happened:
      "Enable-Mailbox : The operation couldn't be performed because 'Test3' matches multiple entries."
  • How to use it to log what was done?
    2 Posts | Last post March 08, 2016
    • Hi,
      Please tell me how to use this function to determine what was done during script running? Based on the script description it looks like it writes down to the log file entered by admin records only. Its that correct? I need to write down all script behaviour during processing.
      PLease reply.
    • http://mrautomaton.com/2015/11/30/psblogweek-building-readable-text-log-files/
      Or use Start-Transcript
  • Reset logfile
    1 Posts | Last post February 18, 2016
    • As a thought, there might be an additional parameter (switch) that will reset/empty the logfile.  I will be using it to perform daily tasks that will use dayofweek.value__ as part of the logfile name and I only want to keep the file until the process runs again the following week. This way the first time that I call the write-log.ps1 I can pass a reset switch along with the other parameters, and then all other calls get message, level and path. Yes I could delete the existing outside of this function, but it seems reasonable to include that ability. 
  • What is the Syntax to import with parameters
    2 Posts | Last post January 21, 2016
    • If I want to source the function into my scripts but set the default value for -Path so that I do not have to specify every time, is there a way to do this other than altering the param value in the write-Log function?
      Something like this:
      #Import logging function
      H:\backup_myDocs\PS-Scripts-a\Function-Write-Log.ps1 -Path="c:\temp\testLog.txt"
    • This script is a function that will require loading into a module or dot sourcing. 
      . c:\scripts\Function-Write-log.ps1
      After you source the function into your script you can set a default path of your log file using $PSDefaultParameterValues.
1 - 10 of 15 Items