PoshCode Logo PowerShell Code Repository

Write-Log by Pat Richard 2 weeks ago (modification of post by Vidrine view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6894"></script>download | new post

Added -NoLog option to write info just to the console
Added -Verbose option to write console output to the verbose handler
Added ValidateSet for $encoding
Added default value for $EventSource
Tweaked the console output when writing an error
Added ValidateRange for $EventId

  1. function Write-Log {  
  2.   [CmdletBinding(SupportsShouldProcess, SupportsPaging)]
  3.   param(
  4.     # The type of message to be logged. Alias is 'type'.
  5.     [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
  6.     [ValidateSet('Error', 'Warn', 'Info', 'Verbose')]
  7.     [ValidateNotNullOrEmpty()]
  8.     [string] $Level = 'Info',
  9.  
  10.     # The message to be logged.
  11.     [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory, HelpMessage = 'No message specified.')]
  12.     [ValidateNotNullOrEmpty()]
  13.     [string] $Message,
  14.  
  15.     # Specifies that $message should not the sent to the log file.
  16.     [Parameter(ValueFromPipelineByPropertyName)]
  17.     [switch] $NoLog,
  18.  
  19.     # Specifies to not display the message to the console.
  20.     [Parameter(ValueFromPipelineByPropertyName)]
  21.     [switch] $NoConsole,
  22.  
  23.     # The number of spaces to indent the message in the log file.
  24.     [Parameter(ValueFromPipelineByPropertyName)]
  25.     [ValidateRange(1,30)]
  26.     [ValidateNotNullOrEmpty()]
  27.     [int] $Indent = 0,
  28.  
  29.     # Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
  30.     [Parameter(ValueFromPipelineByPropertyName)]
  31.     [ValidateSet('Black', 'DarkMagenta', 'DarkRed', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkYellow', 'Red', 'Blue', 'Green', 'Cyan', 'Magenta', 'Yellow', 'DarkGray', 'Gray', 'White')]
  32.     [ValidateNotNullOrEmpty()]
  33.     [String] $ConsoleForeground = 'White',
  34.  
  35.     # Existing log file is deleted when this is specified. Alias is 'Overwrite'.
  36.     [Parameter(ValueFromPipelineByPropertyName)]
  37.     [Switch] $Clobber,
  38.  
  39.     # The name of the system event log, e.g. 'Application'. The Skype for Business log is still called 'Lync Server'. Note that writing to the system event log requires elevated permissions.
  40.     [Parameter(ValueFromPipelineByPropertyName)]
  41.     [ValidateSet('Application', 'System', 'Security', 'Lync Server', 'Microsoft Office Web Apps')]
  42.     [ValidateNotNullOrEmpty()]
  43.     [String] $EventLogName,
  44.  
  45.     # The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
  46.     [Parameter(ValueFromPipelineByPropertyName)]
  47.     [ValidateNotNullOrEmpty()]
  48.     [String] $EventSource = $([IO.FileInfo] $MyInvocation.ScriptName).Name,
  49.  
  50.     # The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
  51.     [Parameter(ValueFromPipelineByPropertyName)]
  52.     [ValidateRange(1,65535)]
  53.     [ValidateNotNullOrEmpty()]
  54.     [int] $EventID = 1,
  55.  
  56.     # The text encoding for the log file. Default is ASCII.
  57.     [Parameter(ValueFromPipelineByPropertyName)]
  58.     [ValidateSet('Unicode','Byte','BigEndianUnicode','UTF8','UTF7','UTF32','ASCII','Default','OEM')]
  59.     [ValidateNotNullOrEmpty()]
  60.     [String] $LogEncoding = 'ASCII'
  61.   ) # end of param block
  62.   BEGIN{} # end BEGIN
  63.   Process{
  64.     try {
  65.       [string]$LogFolder = Split-Path -Path $LogPath -Parent
  66.       if (-not(Test-Path -Path $LogFolder)){
  67.         $null = New-Item -Path $LogFolder -ItemType Directory
  68.       }
  69.       $msg = "{0} : {1} : {2}{3}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level.ToUpper(), ('  ' * $Indent), $Message
  70.       if (-not($NoConsole)){
  71.         switch ($level) {
  72.           'Error' {$Host.UI.WriteErrorLine("$Message")}
  73.           'Warn' {Write-Warning -Message $Message}
  74.           'Info' {Write-Host $Message -ForegroundColor $ConsoleForeground}
  75.           'Verbose' {Write-Verbose -Message $Message}
  76.         }
  77.       }
  78.       if (-not($NoLog)){
  79.         if ($Clobber) {
  80.           $msg | Out-File -FilePath $LogPath -Encoding $LogEncoding -Force
  81.         } else {
  82.           $msg | Out-File -FilePath $LogPath -Encoding $LogEncoding -Append
  83.         }
  84.       }
  85.  
  86.       if ($EventLogName) {
  87.         if (-not $EventSource) {
  88.           [string] $EventSource = $([IO.FileInfo] $MyInvocation.ScriptName).Name
  89.         }
  90.  
  91.         if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) {
  92.           [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName)
  93.         }
  94.  
  95.         switch ($Level) {
  96.           'Error' {$EntryType = 'Error'}
  97.           'Warn'  {$EntryType = 'Warning'}
  98.           'Info'  {$EntryType = 'Information'}
  99.           'Verbose' {$EntryType = 'Information'}
  100.           Default  {$EntryType = 'Information'}
  101.         }
  102.         Write-EventLog -LogName $EventLogName -Source $EventSource -EventId 1 -EntryType $EntryType -Message $Message
  103.       }
  104.       $msg = ''
  105.     } # end try
  106.     catch {
  107.       Throw "Failed to create log entry in: '$LogPath'. The error was: '$_'."
  108.     } # end catch
  109.   } # end PROCESS
  110.   END{} # end END
  111.  
  112.         <#
  113.                 .SYNOPSIS
  114.                         Writes logging information to screen and log file simultaneously.
  115.  
  116.                 .DESCRIPTION
  117.                         Writes logging information to screen and log file simultaneously. Supports multiple log levels.
  118.  
  119.                 .PARAMETER Message
  120.                         The message to be logged.
  121.  
  122.                 .PARAMETER Level
  123.                         The type of message to be logged.
  124.                        
  125.                 .PARAMETER NoConsoleOut
  126.                         Specifies to not display the message to the console.
  127.                        
  128.                 .PARAMETER ConsoleForeground
  129.                         Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
  130.                
  131.                 .PARAMETER Indent
  132.                         The number of spaces to indent the line in the log file.
  133.  
  134.                 .PARAMETER Path
  135.                         The log file path.
  136.                
  137.                 .PARAMETER Clobber
  138.                         Existing log file is deleted when this is specified.
  139.                
  140.                 .PARAMETER EventLogName
  141.                         The name of the system event log, e.g. 'Application'.
  142.                
  143.                 .PARAMETER EventSource
  144.                         The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
  145.                
  146.                 .PARAMETER EventID
  147.                         The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
  148.  
  149.                 .PARAMETER LogEncoding
  150.                         The text encoding for the log file. Default is ASCII.
  151.                
  152.                 .EXAMPLE
  153.                         PS C:\> Write-Log -Message "It's all good!" -Path C:\MyLog.log -Clobber -EventLogName 'Application'
  154.  
  155.                 .EXAMPLE
  156.                         PS C:\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script"
  157.  
  158.                 .INPUTS
  159.                         System.String
  160.  
  161.                 .OUTPUTS
  162.                         No output.
  163.                        
  164.                 .NOTES
  165.                         Revision History:
  166.                                 2011-03-10 : Andy Arismendi - Created.
  167.                                 2011-07-23 : Will Steele - Updated.
  168.                                 2011-07-23 : Andy Arismendi
  169.                                         - Added missing comma in param block.
  170.                                         - Added support for creating missing directories in log file path.
  171.                                 2012-03-10 : Pat Richard
  172.                                         - Added validation sets to $ConsoleForeground and $EventLogName
  173.                                         - Changed formatting of $msg so that only $message is indented instead of entire line (looks cleaner)
  174.                                         - suppressed output when creating path/file
  175.                                 2017-5-14 : Pat Richard
  176.                                         - Added -NoLog option to write info just to the console
  177.                                         - Added -Verbose option to write console output to the verbose handler
  178.                                         - Added ValidateSet for $encoding
  179.                                         - Added default value for $EventSource
  180.                                         - Tweaked the console output when writing an error
  181.         #>
  182. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me