PoshCode Logo PowerShell Code Repository

Difference between
modified post 6894 by Pat Richard on Sun 14th May 23:01 and
original post 3502 by Vidrine on Fri 6th Jul 02:14
Showold version | new version | both versions

    
11
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',
3-
	#region Parameters
10+
    # The message to be logged.
11+
    [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory, HelpMessage = 'No message specified.')]
12+
    [ValidateNotNullOrEmpty()]
13+
    [string] $Message,
5-
		[cmdletbinding()]
15+
    # Specifies that $message should not the sent to the log file.
6-
		Param(
16+
    [Parameter(ValueFromPipelineByPropertyName)]
7-
			[Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
17+
    [switch] $NoLog,
8-
			[string] $Message,
10-
19+
    # Specifies to not display the message to the console.
11-
20+
    [Parameter(ValueFromPipelineByPropertyName)]
21+
    [switch] $NoConsole,
13-
			[Parameter()]
23+
    # The number of spaces to indent the message in the log file.
14-
			[Switch] $NoConsoleOut,
24+
    [Parameter(ValueFromPipelineByPropertyName)]
25+
    [ValidateRange(1,30)]
26+
    [ValidateNotNullOrEmpty()]
27+
    [int] $Indent = 0,
16-
			[Parameter()]
29+
    # Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
17-
			[ValidateSet("Black", "DarkMagenta", "DarkRed", "DarkBlue", "DarkGreen", "DarkCyan", "DarkYellow", "Red", "Blue", "Green", "Cyan", "Magenta", "Yellow", "DarkGray", "Gray", "White")]
30+
    [Parameter(ValueFromPipelineByPropertyName)]
31+
    [ValidateSet('Black', 'DarkMagenta', 'DarkRed', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkYellow', 'Red', 'Blue', 'Green', 'Cyan', 'Magenta', 'Yellow', 'DarkGray', 'Gray', 'White')]
32+
    [ValidateNotNullOrEmpty()]
1833
			[String] $ConsoleForeground = 'White',
20-
			[Parameter()] [ValidateRange(1,30)]
35+
    # Existing log file is deleted when this is specified. Alias is 'Overwrite'.
21-
			[Int16] $Indent = 0,
36+
    [Parameter(ValueFromPipelineByPropertyName)]
37+
    [Switch] $Clobber,
23-
			[Parameter()]
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.
24-
40+
    [Parameter(ValueFromPipelineByPropertyName)]
41+
    [ValidateSet('Application', 'System', 'Security', 'Lync Server', 'Microsoft Office Web Apps')]
42+
    [ValidateNotNullOrEmpty()]
43+
    [String] $EventLogName,
26-
			[Parameter()]
45+
    # The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
27-
			[Switch] $Clobber,
46+
    [Parameter(ValueFromPipelineByPropertyName)]
47+
    [ValidateNotNullOrEmpty()]
48+
    [String] $EventSource = $([IO.FileInfo] $MyInvocation.ScriptName).Name,
29-
			[Parameter()]
50+
    # The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
30-
			[ValidateSet("Application","System","Security")]
51+
    [Parameter(ValueFromPipelineByPropertyName)]
31-
			[String] $EventLogName,
52+
    [ValidateRange(1,65535)]
53+
    [ValidateNotNullOrEmpty()]
54+
    [int] $EventID = 1,
33-
			[Parameter()]
56+
    # The text encoding for the log file. Default is ASCII.
34-
			[String] $EventSource,
57+
    [Parameter(ValueFromPipelineByPropertyName)]
58+
    [ValidateSet('Unicode','Byte','BigEndianUnicode','UTF8','UTF7','UTF32','ASCII','Default','OEM')]
36-
			[Parameter()]
59+
    [ValidateNotNullOrEmpty()]
37-
			[Int32] $EventID = 1,
60+
    [String] $LogEncoding = 'ASCII'
61+
  ) # end of param block
39-
			[Parameter()]
62+
  BEGIN{} # end BEGIN
40-
			[String] $LogEncoding = "ASCII"
63+
  Process{
41-
		)
43-
	#endregion
45-
	Begin {}
47-
	Process {
4864
		try {
49-
			$msg = "{0}`t{1}`t{2}{3}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level.ToUpper(), (" " * $Indent), $Message
65+
      [string]$LogFolder = Split-Path -Path $LogPath -Parent
50-
			if ($NoConsoleOut -eq $false) {
66+
      if (-not(Test-Path -Path $LogFolder)){
51-
				switch ($Level) {
67+
        $null = New-Item -Path $LogFolder -ItemType Directory
52-
					'Error' { Write-Error $Message }
53-
					'Warn' { Write-Warning $Message }
54-
					'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground}
5568
				}
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}
5676
			}
58-
			if (-not $Path.Exists) {
59-
				New-Item -Path $Path.FullName -ItemType File -Force | Out-Null
6077
			}
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+
      }
6279
			if ($Clobber) {
63-
				$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Force
80+
          $msg | Out-File -FilePath $LogPath -Encoding $LogEncoding -Force
6481
			} else {
65-
				$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Append
82+
          $msg | Out-File -FilePath $LogPath -Encoding $LogEncoding -Append
6683
			}
84+
      }
6886
			if ($EventLogName) {
7087
				if (-not $EventSource) {
71-
					$EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name
88+
          [string] $EventSource = $([IO.FileInfo] $MyInvocation.ScriptName).Name
7289
				}
7491
				if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) {
7592
					[Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName)
7693
		        }
78-
				$log = New-Object System.Diagnostics.EventLog
79-
			    $log.set_log($EventLogName)
80-
			    $log.set_source($EventSource)
95+
        switch ($Level) {

ContributeMost Recent Contributions (feed)

Contribute ... Next Page