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
(12)
8,435 times
Add to favorites
4/13/2017
E-mail Twitter del.icio.us Digg Facebook
Sign in to ask a question


  • 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
              [Parameter(Mandatory=$false)] 
              [ValidateSet("Error","Warn","Info")] 
              [string]$LoggingLevel="Info",
      
      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")) ) {
                  break
              }
      
      Through the PSDefaultParameterValues mechanism - we can set the global logging level from the calling script
      $PSDefaultParameterValues=@{"Write-Log:Path"="Logs\MyApp_$today.log";"Write-Log:LoggingLevel"="Error"}
      
      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
      
      cheery, 
      
      Chris
    • 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.
      
      Example:
      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. 
      
      Example:
      . 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.
      
      https://technet.microsoft.com/en-us/library/hh847819.aspx
      
      See
      http://mrautomaton.com/2015/11/30/psblogweek-building-readable-text-log-files/
      
      
  • Adding logging function to script
    4 Posts | Last post January 08, 2016
    • HI,
      I would appreciate if you help me understand few things.
      Under testing environment I run following script which adds a user to Distribution Group.
      
      —–xxx———–xx——
      
      $Owner = Read-Host “Type in Distribution List”
      $User = Read-Host “Type in user to Add”
      
      Add-DistributionGroupMember -Identity $Owner -Member $User
      Write-Host nn`n
      Write-Host “$User has been added to Distribution List $Owner”
      
      —–xxx———–xx——
      
      Before releasing it on production server I want to take some precautionary steps. Let’s say if tomorrow something goes wrong I will have to get in touch with server team to generate log and assess what went wrong; instead if I could integrate ‘Log’ function in the script, every time it will generate log of who executed script, at what time whether it was successful attempt or failure.
      
      I hope to clarify on my requirements, please advise.
    • You can use this Write-Log to log the who executed the script and when. 
      
      Add this to the beginning to your Script.
      Write-Log "Beginning $($MyInvocation.InvocationName) on $($env:COMPUTERNAME) by $env:USERDOMAIN\$env:USERNAME"
      
      See more examples at my blog: 
      http://mrautomaton.com/2015/11/30/psblogweek-building-readable-text-log-files/
    • Thanks for the response. I have added these lines to script but it didn't generate log, I thought of missing out on path declaration so modified it as below-
      $LogFile = 'c:\Temp\scripts.log'
      Write-Log "Beginning $($MyInvocation.InvocationName) on $($env:COMPUTERNAME) by $env:USERDOMAIN\$env:USERNAME" -Path $LogFile
      
      but still could not get log.
      
    • This script is a function that will require loading into a module or dot sourcing. 
      
      Example:
      . c:\scripts\Function-Write-log.ps1
      
      
1 - 10 of 14 Items