From 3a78a84da47f2f33393146fa9e23dda10b11b792 Mon Sep 17 00:00:00 2001 From: timoline Date: Sat, 27 Jul 2019 17:00:02 +0200 Subject: [PATCH 1/2] All kind of changes - log to csv, xml, json, cmtrace - combined cmdlet Write-LogEntry.ps1 - banner switch - more... --- Module/PSLogging/PSLogging.psd1 | Bin 7146 -> 7776 bytes Module/PSLogging/PSLogging.psm1 | 625 +-------------------- Module/PSLogging/private/Get-LogDate.ps1 | 25 + Module/PSLogging/public/Export-Log.ps1 | 39 ++ Module/PSLogging/public/Send-Log.ps1 | 90 +++ Module/PSLogging/public/Start-Log.ps1 | 159 ++++++ Module/PSLogging/public/Stop-Log.ps1 | 146 +++++ Module/PSLogging/public/Write-LogEntry.ps1 | 153 +++++ 8 files changed, 629 insertions(+), 608 deletions(-) create mode 100644 Module/PSLogging/private/Get-LogDate.ps1 create mode 100644 Module/PSLogging/public/Export-Log.ps1 create mode 100644 Module/PSLogging/public/Send-Log.ps1 create mode 100644 Module/PSLogging/public/Start-Log.ps1 create mode 100644 Module/PSLogging/public/Stop-Log.ps1 create mode 100644 Module/PSLogging/public/Write-LogEntry.ps1 diff --git a/Module/PSLogging/PSLogging.psd1 b/Module/PSLogging/PSLogging.psd1 index 9a90be10df51b423f918adb6c8ac3e5ef5507fd2..901c8007c21f4cdb116ddeddbf05b26ba1dfa86e 100755 GIT binary patch delta 1222 zcmZ`&O>7cT5FQEzTA;uJg)JT+8V$BkN<;9ch=e9>{b`D(TI0bVtbnBz+tR9s8e%lj zgRzbmqlwlgJsA&rF|iypdhnpp#3mlq#EVB`Jb7?<>`pgPvw1t;`)20Nm-lAACqDPx z{Amh+_%LX7p;0&IQubhj)`kZHcuD8At9-*I7gJt*taIZApBZ23`gf}C{csjeK?O=M z4u@z>!weLOn^F%Wo20b`dLaT)T0Q9Wxv;NkETo<>0HZJj{hAEbqgcG#bW~LS)fDSd zeQByX3k9k*{ohPcd9msbby3J+3Oxfkk~dEO0x<`bU0w1N37>$X5O-WZ$l@}TH3?-n zK@k^VnCv9wt0Kr^O&=HHe&~n!c2fqAO%p>=S;K^gS~Z++79Ok_{4E@VL(S)e|EoEM zWz%MqjJx@?tg*9MT%S;P)wsZ(52he)GIeM&PilN=!As^F%-uIw)i99i7 zBav6NlX6pA9hdX+5i9m delta 520 zcmYLG!D3^M30=AH3ZgvDJBRb`y$|j=EF53l=(K*V zCu5}3b$Y;Om9Fu98>QhP?D~iA?MF!G19kOwxc-T`cltN3`4n4+B zNZ@w3j=k_}G}J6+G#zdADOVe+jZrOv`G~`>K2FraKX-(kESlOPPP8f35)HkMZ+aF^ zw27_g1Uk`ew7Wh0?0$|Xu>y8uyIAiT!>67#RD1Jy+4};bZw!9ldpL%~4Wo)J!^5#r zLD3w-XT#**zL*JQ;+L>*dNAV^ZITyupYGB_d^OKvGwwsNCQz{!@Xk8V>>`|)LNzh+ zb}iutaM&-P*a8_lhk1JkDWM}TX3!K1=!gu8&IaogJ`PmjIBnMb`0m`q)npzA$rLt| zqs$)exB}80W-j54TeQ - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$LogPath, - [Parameter(Mandatory=$true,Position=1)][string]$LogName, - [Parameter(Mandatory=$true,Position=2)][string]$ScriptVersion, - [Parameter(Mandatory=$false,Position=3)][switch]$ToScreen - ) - - Process { - $sFullPath = Join-Path -Path $LogPath -ChildPath $LogName - - #Check if file exists and delete if it does - If ( (Test-Path -Path $sFullPath) ) { - Remove-Item -Path $sFullPath -Force +# region Load of module functions +$PublicFunctions = @( Get-ChildItem -Path $PSScriptRoot\public\*.ps1 -ErrorAction SilentlyContinue ) +$PrivateFunctions = @( Get-ChildItem -Path $PSScriptRoot\private\*.ps1 -ErrorAction SilentlyContinue ) + +# Load the separate function files from the private and public folders. +$AllFunctions = $PublicFunctions + $PrivateFunctions +foreach ($function in $AllFunctions) +{ + try + { + . $function.Fullname + } + catch + { + Write-Error -Message "Failed to import function $($function.fullname): $_" } - - #Create file and start logging - New-Item -Path $sFullPath –ItemType File - - Add-Content -Path $sFullPath -Value "***************************************************************************************************" - Add-Content -Path $sFullPath -Value "Started processing at [$([DateTime]::Now)]." - Add-Content -Path $sFullPath -Value "***************************************************************************************************" - Add-Content -Path $sFullPath -Value "" - Add-Content -Path $sFullPath -Value "Running script version [$ScriptVersion]." - Add-Content -Path $sFullPath -Value "" - Add-Content -Path $sFullPath -Value "***************************************************************************************************" - Add-Content -Path $sFullPath -Value "" - - #Write to screen for debug mode - Write-Debug "***************************************************************************************************" - Write-Debug "Started processing at [$([DateTime]::Now)]." - Write-Debug "***************************************************************************************************" - Write-Debug "" - Write-Debug "Running script version [$ScriptVersion]." - Write-Debug "" - Write-Debug "***************************************************************************************************" - Write-Debug "" - - #Write to scren for ToScreen mode - If ( $ToScreen -eq $True ) { - Write-Output "***************************************************************************************************" - Write-Output "Started processing at [$([DateTime]::Now)]." - Write-Output "***************************************************************************************************" - Write-Output "" - Write-Output "Running script version [$ScriptVersion]." - Write-Output "" - Write-Output "***************************************************************************************************" - Write-Output "" - } - } } -Function Write-LogInfo { - <# - .SYNOPSIS - Writes informational message to specified log file - - .DESCRIPTION - Appends a new informational message to the specified log file - - .PARAMETER LogPath - Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log - - .PARAMETER Message - Mandatory. The string that you want to write to the log - - .PARAMETER TimeStamp - Optional. When parameter specified will append the current date and time to the end of the line. Useful for knowing - when a task started and stopped. - - .PARAMETER ToScreen - Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional - another option to write content to screen as opposed to using debug mode. - - .INPUTS - Parameters above - - .OUTPUTS - None - - .NOTES - Version: 1.0 - Author: Luca Sturlese - Creation Date: 10/05/12 - Purpose/Change: Initial function development. - - Version: 1.1 - Author: Luca Sturlese - Creation Date: 19/05/12 - Purpose/Change: Added debug mode support. - - Version: 1.2 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed function name to use approved PowerShell Verbs. Improved help documentation. - - Version: 1.3 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed parameter name from LineValue to Message to improve consistency across functions. - - Version: 1.4 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -TimeStamp parameter which append a timestamp to the end of the line. Useful for knowing when a task started and stopped. - - Version: 1.5 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -ToScreen parameter which will display content to screen as well as write to the log file. - - .LINK - http://9to5IT.com/powershell-logging-v2-easily-create-log-files - - .EXAMPLE - Write-LogInfo -LogPath "C:\Windows\Temp\Test_Script.log" -Message "This is a new line which I am appending to the end of the log file." - - Writes a new informational log message to a new line in the specified log file. - #> - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$LogPath, - [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)][string]$Message, - [Parameter(Mandatory=$false,Position=2)][switch]$TimeStamp, - [Parameter(Mandatory=$false,Position=3)][switch]$ToScreen - ) - - Process { - #Add TimeStamp to message if specified - If ( $TimeStamp -eq $True ) { - $Message = "$Message [$([DateTime]::Now)]" - } - - #Write Content to Log - Add-Content -Path $LogPath -Value $Message - - #Write to screen for debug mode - Write-Debug $Message - - #Write to scren for ToScreen mode - If ( $ToScreen -eq $True ) { - Write-Output $Message - } - } -} - -Function Write-LogWarning { - <# - .SYNOPSIS - Writes warning message to specified log file - - .DESCRIPTION - Appends a new warning message to the specified log file. Automatically prefixes line with WARNING: - - .PARAMETER LogPath - Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log - - .PARAMETER Message - Mandatory. The string that you want to write to the log - - .PARAMETER TimeStamp - Optional. When parameter specified will append the current date and time to the end of the line. Useful for knowing - when a task started and stopped. - - .PARAMETER ToScreen - Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional - another option to write content to screen as opposed to using debug mode. - - .INPUTS - Parameters above - - .OUTPUTS - None - - .NOTES - Version: 1.0 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Initial function development. - - Version: 1.1 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -TimeStamp parameter which append a timestamp to the end of the line. Useful for knowing when a task started and stopped. - - Version: 1.2 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -ToScreen parameter which will display content to screen as well as write to the log file. - - .LINK - http://9to5IT.com/powershell-logging-v2-easily-create-log-files - - .EXAMPLE - Write-LogWarning -LogPath "C:\Windows\Temp\Test_Script.log" -Message "This is a warning message." - - Writes a new warning log message to a new line in the specified log file. - #> - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$LogPath, - [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)][string]$Message, - [Parameter(Mandatory=$false,Position=2)][switch]$TimeStamp, - [Parameter(Mandatory=$false,Position=3)][switch]$ToScreen - ) - - Process { - #Add TimeStamp to message if specified - If ( $TimeStamp -eq $True ) { - $Message = "$Message [$([DateTime]::Now)]" - } - - #Write Content to Log - Add-Content -Path $LogPath -Value "WARNING: $Message" - - #Write to screen for debug mode - Write-Debug "WARNING: $Message" - - #Write to scren for ToScreen mode - If ( $ToScreen -eq $True ) { - Write-Output "WARNING: $Message" - } - } -} - -Function Write-LogError { - <# - .SYNOPSIS - Writes error message to specified log file - - .DESCRIPTION - Appends a new error message to the specified log file. Automatically prefixes line with ERROR: - - .PARAMETER LogPath - Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log - - .PARAMETER Message - Mandatory. The description of the error you want to pass (pass your own or use $_.Exception) - - .PARAMETER TimeStamp - Optional. When parameter specified will append the current date and time to the end of the line. Useful for knowing - when a task started and stopped. - - .PARAMETER ExitGracefully - Optional. If parameter specified, then runs Stop-Log and then exits script - - .PARAMETER ToScreen - Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional - another option to write content to screen as opposed to using debug mode. - - .INPUTS - Parameters above - - .OUTPUTS - None - - .NOTES - Version: 1.0 - Author: Luca Sturlese - Creation Date: 10/05/12 - Purpose/Change: Initial function development. - - Version: 1.1 - Author: Luca Sturlese - Creation Date: 19/05/12 - Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality. - - Version: 1.2 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed function name to use approved PowerShell Verbs. Improved help documentation. - - Version: 1.3 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed parameter name from ErrorDesc to Message to improve consistency across functions. - - Version: 1.4 - Author: Luca Sturlese - Creation Date: 03/09/15 - Purpose/Change: Improved readability and cleaniness of error writing. - - Version: 1.5 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Changed -ExitGracefully parameter to switch type so no longer need to specify $True or $False (see example for info). - - Version: 1.6 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -TimeStamp parameter which append a timestamp to the end of the line. Useful for knowing when a task started and stopped. - - Version: 1.7 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -ToScreen parameter which will display content to screen as well as write to the log file. - - .LINK - http://9to5IT.com/powershell-logging-v2-easily-create-log-files - - .EXAMPLE - Write-LogError -LogPath "C:\Windows\Temp\Test_Script.log" -Message $_.Exception -ExitGracefully - - Writes a new error log message to a new line in the specified log file. Once the error has been written, - the Stop-Log function is excuted and the calling script is exited. - - .EXAMPLE - Write-LogError -LogPath "C:\Windows\Temp\Test_Script.log" -Message $_.Exception - - Writes a new error log message to a new line in the specified log file, but does not execute the Stop-Log - function, nor does it exit the calling script. In other words, the only thing that occurs is an error message - is written to the log file and that is it. - - Note: If you don't specify the -ExitGracefully parameter, then the script will not exit on error. - #> - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$LogPath, - [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)][string]$Message, - [Parameter(Mandatory=$false,Position=3)][switch]$TimeStamp, - [Parameter(Mandatory=$false,Position=4)][switch]$ExitGracefully, - [Parameter(Mandatory=$false,Position=5)][switch]$ToScreen - ) - - Process { - #Add TimeStamp to message if specified - If ( $TimeStamp -eq $True ) { - $Message = "$Message [$([DateTime]::Now)]" - } - - #Write Content to Log - Add-Content -Path $LogPath -Value "ERROR: $Message" - - #Write to screen for debug mode - Write-Debug "ERROR: $Message" - - #Write to scren for ToScreen mode - If ( $ToScreen -eq $True ) { - Write-Output "ERROR: $Message" - } - - #If $ExitGracefully = True then run Log-Finish and exit script - If ( $ExitGracefully -eq $True ){ - Add-Content -Path $LogPath -Value " " - Stop-Log -LogPath $LogPath - Break - } - } -} - -Function Stop-Log { - <# - .SYNOPSIS - Write closing data to log file & exits the calling script - - .DESCRIPTION - Writes finishing logging data to specified log file and then exits the calling script - - .PARAMETER LogPath - Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log - - .PARAMETER NoExit - Optional. If parameter specified, then the function will not exit the calling script, so that further execution can occur (like Send-Log) - - .PARAMETER ToScreen - Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional - another option to write content to screen as opposed to using debug mode. - - .INPUTS - Parameters above - - .OUTPUTS - None - - .NOTES - Version: 1.0 - Author: Luca Sturlese - Creation Date: 10/05/12 - Purpose/Change: Initial function development. - - Version: 1.1 - Author: Luca Sturlese - Creation Date: 19/05/12 - Purpose/Change: Added debug mode support. - - Version: 1.2 - Author: Luca Sturlese - Creation Date: 01/08/12 - Purpose/Change: Added option to not exit calling script if required (via optional parameter). - - Version: 1.3 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed function name to use approved PowerShell Verbs. Improved help documentation. - - Version: 1.4 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Changed -NoExit parameter to switch type so no longer need to specify $True or $False (see example for info). - - Version: 1.5 - Author: Luca Sturlese - Creation Date: 12/09/15 - Purpose/Change: Added -ToScreen parameter which will display content to screen as well as write to the log file. - - .LINK - http://9to5IT.com/powershell-logging-v2-easily-create-log-files - - .EXAMPLE - Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" - - Writes the closing logging information to the log file and then exits the calling script. - - Note: If you don't specify the -NoExit parameter, then the script will exit the calling script. - - .EXAMPLE - Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit - - Writes the closing logging information to the log file but does not exit the calling script. This then - allows you to continue executing additional functionality in the calling script (such as calling the - Send-Log function to email the created log to users). - #> - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$LogPath, - [Parameter(Mandatory=$false,Position=1)][switch]$NoExit, - [Parameter(Mandatory=$false,Position=2)][switch]$ToScreen - ) - - Process { - Add-Content -Path $LogPath -Value "" - Add-Content -Path $LogPath -Value "***************************************************************************************************" - Add-Content -Path $LogPath -Value "Finished processing at [$([DateTime]::Now)]." - Add-Content -Path $LogPath -Value "***************************************************************************************************" - - #Write to screen for debug mode - Write-Debug "" - Write-Debug "***************************************************************************************************" - Write-Debug "Finished processing at [$([DateTime]::Now)]." - Write-Debug "***************************************************************************************************" - - #Write to scren for ToScreen mode - If ( $ToScreen -eq $True ) { - Write-Output "" - Write-Output "***************************************************************************************************" - Write-Output "Finished processing at [$([DateTime]::Now)]." - Write-Output "***************************************************************************************************" - } - - #Exit calling script if NoExit has not been specified or is set to False - If( !($NoExit) -or ($NoExit -eq $False) ){ - Exit - } - } -} - -Function Send-Log { - <# - .SYNOPSIS - Emails completed log file to list of recipients - - .DESCRIPTION - Emails the contents of the specified log file to a list of recipients - - .PARAMETER SMTPServer - Mandatory. FQDN of the SMTP server used to send the email. Example: smtp.google.com - - .PARAMETER LogPath - Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log - - .PARAMETER EmailFrom - Mandatory. The email addresses of who you want to send the email from. Example: "admin@9to5IT.com" - - .PARAMETER EmailTo - Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "admin@9to5IT.com, test@test.com" - - .PARAMETER EmailSubject - Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]" - - .INPUTS - Parameters above - - .OUTPUTS - Email sent to the list of addresses specified - - .NOTES - Version: 1.0 - Author: Luca Sturlese - Creation Date: 05.10.12 - Purpose/Change: Initial function development. - - Version: 1.1 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Changed function name to use approved PowerShell Verbs. Improved help documentation. - - Version: 1.2 - Author: Luca Sturlese - Creation Date: 02/09/15 - Purpose/Change: Added SMTPServer parameter to pass SMTP server as oppposed to having to set it in the function manually. - - .LINK - http://9to5IT.com/powershell-logging-v2-easily-create-log-files - - .EXAMPLE - Send-Log -SMTPServer "smtp.google.com" -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "admin@9to5IT.com" -EmailTo "admin@9to5IT.com, test@test.com" -EmailSubject "Cool Script" - - Sends an email with the contents of the log file as the body of the email. Sends the email from admin@9to5IT.com and sends - the email to admin@9to5IT.com and test@test.com email addresses. The email has the subject of Cool Script. The email is - sent using the smtp.google.com SMTP server. - #> - - [CmdletBinding()] - - Param ( - [Parameter(Mandatory=$true,Position=0)][string]$SMTPServer, - [Parameter(Mandatory=$true,Position=1)][string]$LogPath, - [Parameter(Mandatory=$true,Position=2)][string]$EmailFrom, - [Parameter(Mandatory=$true,Position=3)][string]$EmailTo, - [Parameter(Mandatory=$true,Position=4)][string]$EmailSubject - ) - - Process { - Try { - $sBody = ( Get-Content $LogPath | Out-String ) - - #Create SMTP object and send email - $oSmtp = new-object Net.Mail.SmtpClient( $SMTPServer ) - $oSmtp.Send( $EmailFrom, $EmailTo, $EmailSubject, $sBody ) - Exit 0 - } - - Catch { - Exit 1 - } - } -} \ No newline at end of file +# Export the public functions +Export-ModuleMember -Function $PublicFunctions.BaseName diff --git a/Module/PSLogging/private/Get-LogDate.ps1 b/Module/PSLogging/private/Get-LogDate.ps1 new file mode 100644 index 0000000..77f0d0e --- /dev/null +++ b/Module/PSLogging/private/Get-LogDate.ps1 @@ -0,0 +1,25 @@ +function Get-LogDate { + <# + .SYNOPSIS + Creates a Date and Timestamp to be used in log file creation + .DESCRIPTION + Creates a nicely formatted timestamp for use in log creation + .PARAMETER Format + Displays the date and time in the Microsoft .NET Framework format indicated by the format specifier. + Enter a format specifier. For a list of available format specifiers, see DateTimeFormatInfo Class http://msdn.microsoft.com/library/system.globalization.datetimeformatinfo.aspx (http://msdn.microsoft.com/library/system.globalization.datetimeformatinfo.aspx) in MSDN. + .EXAMPLE + Get-LogDate + .EXAMPLE + Get-LogDate -Format 'yyyy-MM-dd HH:mm:ss' + .EXAMPLE + Get-LogDate + .NOTES + Default formatting if no formatting provided: 'yyyy-MM-dd HH:mm:ss' + #> + Param( + [Parameter(Position=0)] + [String]$Format = 'MM-dd-yyyy HH:mm:ss.ffffff' + ) + + Get-Date -Format ("{0}" -f $Format) +} \ No newline at end of file diff --git a/Module/PSLogging/public/Export-Log.ps1 b/Module/PSLogging/public/Export-Log.ps1 new file mode 100644 index 0000000..f836911 --- /dev/null +++ b/Module/PSLogging/public/Export-Log.ps1 @@ -0,0 +1,39 @@ +function Export-Log +{ + param ( + [Parameter(Mandatory = $true, Position = 0)] + [string]$LogPath, + [Parameter(Mandatory = $true, Position = 1)] + [string]$Outfile, + [Parameter(Mandatory = $true, Position = 2)] + [ValidateSet("Csv", "Json", "Xml")] + [string]$Format + ) + + $Data = Import-Csv -Path $LogPath -Delimiter ";" -Header TimeStamp, MessageType, Message #needs foutafhandeling + + if ($Data) + { + if ($Format -eq "Csv") + { + $Data | Export-Csv $Outfile -UseCulture -NoTypeInformation + } + + if ($Format -eq "Json") + { + $Data | ConvertTo-Json | Out-File $Outfile + } + + if ($Format -eq "Xml") + { + $Data | Export-Clixml $Outfile + } + } + else + { + Write-Error "Cannot export, no data or not a correct log file" + } +} + + + diff --git a/Module/PSLogging/public/Send-Log.ps1 b/Module/PSLogging/public/Send-Log.ps1 new file mode 100644 index 0000000..b4346dc --- /dev/null +++ b/Module/PSLogging/public/Send-Log.ps1 @@ -0,0 +1,90 @@ +Function Send-Log +{ + <# + .SYNOPSIS + Emails completed log file to list of recipients + + .DESCRIPTION + Emails the contents of the specified log file to a list of recipients + + .PARAMETER SMTPServer + Mandatory. FQDN of the SMTP server used to send the email. Example: smtp.google.com + + .PARAMETER LogPath + Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log + + .PARAMETER EmailFrom + Mandatory. The email addresses of who you want to send the email from. Example: "admin@9to5IT.com" + + .PARAMETER EmailTo + Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "admin@9to5IT.com, test@test.com" + + .PARAMETER EmailSubject + Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]" + + .INPUTS + Parameters above + + .OUTPUTS + Email sent to the list of addresses specified + + .NOTES + Version: 1.0 + Author: Luca Sturlese + Creation Date: 05.10.12 + Purpose/Change: Initial function development. + + Version: 1.1 + Author: Luca Sturlese + Creation Date: 02/09/15 + Purpose/Change: Changed function name to use approved PowerShell Verbs. Improved help documentation. + + Version: 1.2 + Author: Luca Sturlese + Creation Date: 02/09/15 + Purpose/Change: Added SMTPServer parameter to pass SMTP server as oppposed to having to set it in the function manually. + + .LINK + http://9to5IT.com/powershell-logging-v2-easily-create-log-files + + .EXAMPLE + Send-Log -SMTPServer "smtp.google.com" -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "admin@9to5IT.com" -EmailTo "admin@9to5IT.com, test@test.com" -EmailSubject "Cool Script" + + Sends an email with the contents of the log file as the body of the email. Sends the email from admin@9to5IT.com and sends + the email to admin@9to5IT.com and test@test.com email addresses. The email has the subject of Cool Script. The email is + sent using the smtp.google.com SMTP server. + #> + + [CmdletBinding()] + + Param ( + [Parameter(Mandatory = $true, Position = 0)] + [string]$SMTPServer, + [Parameter(Mandatory = $true, Position = 1)] + [string]$LogPath, + [Parameter(Mandatory = $true, Position = 2)] + [string]$EmailFrom, + [Parameter(Mandatory = $true, Position = 3)] + [string]$EmailTo, + [Parameter(Mandatory = $true, Position = 4)] + [string]$EmailSubject + ) + + Process + { + Try + { + $sBody = ( Get-Content $LogPath | Out-String ) + + #Create SMTP object and send email + $oSmtp = New-Object Net.Mail.SmtpClient( $SMTPServer ) + $oSmtp.Send( $EmailFrom, $EmailTo, $EmailSubject, $sBody ) + Exit 0 + } + + Catch + { + Exit 1 + } + } +} \ No newline at end of file diff --git a/Module/PSLogging/public/Start-Log.ps1 b/Module/PSLogging/public/Start-Log.ps1 new file mode 100644 index 0000000..1591130 --- /dev/null +++ b/Module/PSLogging/public/Start-Log.ps1 @@ -0,0 +1,159 @@ +Function Start-Log +{ + <# + .SYNOPSIS + Creates a new log file + + .DESCRIPTION + Creates a log file with the path and name specified in the parameters. Checks if log file exists, and if it does deletes it and creates a new one. + Once created, writes initial logging data + + .PARAMETER LogPath + Mandatory. Path of where log is to be created. Example: C:\Windows\Temp + + .PARAMETER LogName + Mandatory. Name of log file to be created. Example: Test_Script.log + + .PARAMETER ScriptVersion + Mandatory. Version of the running script which will be written in the log. Example: 1.5 + + .PARAMETER ToScreen + Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional + another option to write content to screen as opposed to using debug mode. + + .INPUTS + Parameters above + + .OUTPUTS + Log file created + + .NOTES + + .LINK + http://9to5IT.com/powershell-logging-v2-easily-create-log-files + + .EXAMPLE + Start-Log -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5" + + Creates a new log file with the file path of C:\Windows\Temp\Test_Script.log. Initialises the log file with + the date and time the log was created (or the calling script started executing) and the calling script's version. + #> + + [CmdletBinding()] + + Param ( + [Parameter(Mandatory = $true, Position = 0)] + [ValidateSet("log", "csv", "json", "xml", "cmtrace")] + [string]$LogFormat, + [Parameter(Mandatory = $true, Position = 1)] + [string]$LogPath, + [Parameter(Mandatory = $true, Position = 2)] + [string]$LogName, + [Parameter(Mandatory = $true, Position = 3)] + [string]$ScriptVersion, + [Parameter(Mandatory = $false, Position = 4)] + [switch]$ToScreen, + [Parameter(Mandatory = $false)] + [switch]$ToEventLog, + [Parameter(Mandatory = $false)] + [switch]$Banner + ) + + Process + { + $sFullPath = Join-Path -Path $LogPath -ChildPath $LogName + + $Msg = [PSCustomObject]@{ + TimeStamp = Get-LogDate + MessageType = "INFO" + Message = "Started processing at [$(Get-LogDate)]." + } + + if($LogFormat -eq "log") + { + #Check if file exists and delete if it does + If ( (Test-Path -Path $sFullPath) ) + { + Remove-Item -Path $sFullPath -Force + } + + #Create file and start logging + New-Item -Path $sFullPath -ItemType File + } + + #Write Content to Log + If ( $Banner -eq $True ) + { + if ($LogFormat -eq "log") + { + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;***************************************************************************************************" + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;Started processing at [$(Get-LogDate)]." + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;***************************************************************************************************" + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;" + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;Running script version [$ScriptVersion]." + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;" + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;***************************************************************************************************" + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;" + } + } + else + { + if ($LogFormat -eq "log") + { + Add-Content -Path $sFullPath -Value "$(Get-LogDate);INFO;Started processing at [$(Get-LogDate)]." + } + + if ($LogFormat -eq "xml") + { + $Msg | Export-Clixml $sFullPath + } + + if ($LogFormat -eq "json") + { + $Msg | ConvertTo-Json | Out-File $sFullPath + } + + if ($LogFormat -eq "csv") + { + $Msg | Export-Csv $sFullPath -UseCulture -NoTypeInformation + } + + if ($LogFormat -eq "cmtrace") + { + $toLog = "{0} `$$<{1}><{2}>" -f ($Msg.MessageType + ":" + $Msg.Message), $LogName, $Msg.TimeStamp, $pid + $toLog | Out-File -Append -Encoding UTF8 -FilePath $sFullPath + } + } + + #Write Content to the EventViewer + If ( $ToEventLog -eq $True ) + { + $LogBaseName = Get-Item $sFullPath | Select-Object -ExpandProperty BaseName + New-EventLog -LogName "Application" -Source $LogBaseName # needs fix if already exists + Write-EventLog -LogName "Application" -Source $LogBaseName -EventID 3001 -EntryType Information -Message "$($LogBaseName) $($ScriptVersion) started" -Category 1 + } + + #Write to screen for debug mode + Write-Debug "***************************************************************************************************" + Write-Debug "Started processing at [$(Get-LogDate)]." + Write-Debug "***************************************************************************************************" + Write-Debug "" + Write-Debug "Running script version [$ScriptVersion]." + Write-Debug "" + Write-Debug "***************************************************************************************************" + Write-Debug "" + + #Write to screen for ToScreen mode + If ( $ToScreen -eq $True ) + { + Write-Output "***************************************************************************************************" + Write-Output "Started processing at [$(Get-LogDate)]." + Write-Output "***************************************************************************************************" + Write-Output "" + Write-Output "Running script version [$ScriptVersion]." + Write-Output "" + Write-Output "***************************************************************************************************" + Write-Output "" + } + } +} \ No newline at end of file diff --git a/Module/PSLogging/public/Stop-Log.ps1 b/Module/PSLogging/public/Stop-Log.ps1 new file mode 100644 index 0000000..c4a2ed0 --- /dev/null +++ b/Module/PSLogging/public/Stop-Log.ps1 @@ -0,0 +1,146 @@ +Function Stop-Log +{ + <# + .SYNOPSIS + Write closing data to log file & exits the calling script + + .DESCRIPTION + Writes finishing logging data to specified log file and then exits the calling script + + .PARAMETER LogPath + Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log + + .PARAMETER NoExit + Optional. If parameter specified, then the function will not exit the calling script, so that further execution can occur (like Send-Log) + + .PARAMETER ToScreen + Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional + another option to write content to screen as opposed to using debug mode. + + .INPUTS + Parameters above + + .OUTPUTS + None + + .NOTES + + .LINK + http://9to5IT.com/powershell-logging-v2-easily-create-log-files + + .EXAMPLE + Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" + + Writes the closing logging information to the log file and then exits the calling script. + + Note: If you don't specify the -NoExit parameter, then the script will exit the calling script. + + .EXAMPLE + Stop-Log -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit + + Writes the closing logging information to the log file but does not exit the calling script. This then + allows you to continue executing additional functionality in the calling script (such as calling the + Send-Log function to email the created log to users). + #> + + [CmdletBinding()] + + Param ( + [Parameter(Mandatory = $true)] + [ValidateSet("log", "csv", "json", "xml", "cmtrace")] + [string]$LogFormat, + [Parameter(Mandatory = $true, Position = 0)] + [string]$LogPath, + [Parameter(Mandatory = $false, Position = 1)] + [switch]$NoExit, + [Parameter(Mandatory = $false, Position = 2)] + [switch]$ToScreen, + [Parameter(Mandatory = $false)] + [switch]$ToEventLog, + [Parameter(Mandatory = $false)] + [switch]$Banner + ) + + Process + { + + $Msg = [PSCustomObject]@{ + TimeStamp = Get-LogDate + MessageType = "INFO" + Message = "Finished processing at [$(Get-LogDate)]." + } + + #Write Content to Log + If ( $Banner -eq $True ) + { + if($LogFormat -eq "log") + { + Add-Content -Path $LogPath -Value "$(Get-LogDate);INFO;" + Add-Content -Path $LogPath -Value "$(Get-LogDate);INFO;***************************************************************************************************" + Add-Content -Path $LogPath -Value "$(Get-LogDate);INFO;Finished processing at [$(Get-LogDate)]." + Add-Content -Path $LogPath -Value "$(Get-LogDate);INFO;***************************************************************************************************" + } + } + else + { + if($LogFormat -eq "log") + { + Add-Content -Path $LogPath -Value "$(Get-LogDate);INFO;Finished processing at [$(Get-LogDate)]." + } + + if($LogFormat -eq "xml") + { + [array]$Log = Import-Clixml $LogPath + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | Export-Clixml $LogPath + } + + if($LogFormat -eq "json") + { + [array]$Log = Get-Content $LogPath | ConvertFrom-Json + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | ConvertTo-Json | Out-File $LogPath + } + + if ($LogFormat -eq "csv") + { + [array]$Log = Import-Csv $LogPath + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | Export-Csv $LogPath -UseCulture -NoTypeInformation + } + if ($LogFormat -eq "cmtrace") + { + $toLog = "{0} `$$<{1}><{2}>" -f ($Msg.MessageType + ":" + $Msg.Message), $LogName, $Msg.TimeStamp, $pid + $toLog | Out-File -Append -Encoding UTF8 -FilePath $LogPath + } + } + + #Write Content to the EventViewer + If ( $ToEventLog -eq $True ) + { + $LogBaseName = Get-Item $LogPath | Select-Object -ExpandProperty BaseName + Write-EventLog -LogName "Application" -Source $LogBaseName -EventID 3001 -EntryType Information -Message "$($LogBaseName) finished" -Category 1 + } + + #Write to screen for debug mode + Write-Debug "" + Write-Debug "***************************************************************************************************" + Write-Debug "Finished processing at [$(Get-LogDate)]." + Write-Debug "***************************************************************************************************" + + #Write to screen for ToScreen mode + If ( $ToScreen -eq $True ) + { + Write-Output "" + Write-Output "***************************************************************************************************" + Write-Output "Finished processing at [$(Get-LogDate)]." + Write-Output "***************************************************************************************************" + } + + #Exit calling script if NoExit has not been specified or is set to False + If ( !($NoExit) -or ($NoExit -eq $False) ) + { + Exit + } + } +} diff --git a/Module/PSLogging/public/Write-LogEntry.ps1 b/Module/PSLogging/public/Write-LogEntry.ps1 new file mode 100644 index 0000000..2324134 --- /dev/null +++ b/Module/PSLogging/public/Write-LogEntry.ps1 @@ -0,0 +1,153 @@ +Function Write-LogEntry +{ + <# + .SYNOPSIS + Writes a message to specified log file + .DESCRIPTION + Appends a new message to the specified log file + .PARAMETER LogPath + Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log + + .PARAMETER MessageType + Mandatory. Allowed message types: INFO, WARNING, ERROR, CRITICAL, START, STOP, SUCCESS, FAILURE + .PARAMETER Message + Mandatory. The string that you want to write to the log + .PARAMETER TimeStamp + Optional. When parameter specified will append the current date and time to the end of the line. Useful for knowing + when a task started and stopped. + + .PARAMETER EntryDateTime + Optional. By default a current date and time is used but it is possible provide any other correct date/time. + + .PARAMETER ToScreen + Optional. When parameter specified will display the content to screen as well as write to log file. This provides an additional + another option to write content to screen as opposed to using debug mode. + + .PARAMETER + .INPUTS + Parameters above + .OUTPUTS + None or String + .NOTES + + Current version: 1.2.0 + + Authors: + - Wojciech Sciesinski wojciech[at]sciesinski[dot]net + + Version history: github.com/9to5IT/PSLogging/VERSIONS.MD + + Inspired and partially based on PSLogging module authored by Luca Sturlese - https://github.com/9to5IT/PSLogging + + .LINK + http://9to5IT.com/powershell-logging-v2-easily-create-log-files + .LINK + https://github.com/it-praktyk/PSLogging + + .LINK + https://www.linkedin.com/in/sciesinskiwojciech + + .EXAMPLE + Write-LogEntry -LogPath "C:\Windows\Temp\Test_Script.log" -MessageType CRITICAL -Message "This is a new line which I am appending to the end of the log file." + Writes a new critical log message to a new line in the specified log file. + + #> + + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $false, ParameterSetName = "WriteToFile")] + [ValidateSet("log", "csv", "json", "xml", "cmtrace")] + [string]$LogFormat, + [Parameter(Mandatory = $false, ParameterSetName = "WriteToFile")] + [Switch]$ToFile, + [Parameter(Mandatory = $false, ParameterSetName = "WriteToFile")] + [string]$LogPath, + [Parameter(Mandatory = $false)] + [switch]$ToScreen, + [Parameter(Mandatory = $false)] + [switch]$ToEventLog, + [Parameter(Mandatory = $true, HelpMessage = "Allowed values: INFO, WARNING, ERROR")] + [ValidateSet("INFO", "WARNING", "ERROR")] + [String]$MessageType = "INFO", + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] + [Alias("EventMessage", "EntryMessage")] + [string]$Message + ) + + Process + { + + $Msg = [PSCustomObject]@{ + TimeStamp = Get-LogDate + MessageType = $MessageType.ToUpper() + Message = $Message + } + + $MessageToFile = "{0};{1};{2}" -f $Msg.TimeStamp, $Msg.MessageType, $Msg.Message + $MessageToScreen = "[{0}] {1}: {2}" -f $Msg.TimeStamp, $Msg.MessageType, $Msg.Message + + #Write Content to Log + If ($ToFile -eq $true) + { + if ($LogFormat -eq "log") + { + Add-Content -Path $LogPath -Value $MessageToFile + } + + if ($LogFormat -eq "xml") + { + + [array]$Log = Import-Clixml $LogPath + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | Export-Clixml $LogPath + } + + if ($LogFormat -eq "json") + { + [array]$Log = Get-Content $LogPath | ConvertFrom-Json + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | ConvertTo-Json | Out-File $LogPath + } + + if ($LogFormat -eq "csv") + { + [array]$Log = Import-Csv $LogPath + $Log += $Msg | Select-Object TimeStamp, MessageType, Message + $Log | Export-Csv $LogPath -UseCulture -NoTypeInformation + } + + if ($LogFormat -eq "cmtrace") + { + $toLog = "{0} `$$<{1}><{2}>" -f ($Msg.MessageType + ":" + $Msg.Message), $LogPath, $Msg.TimeStamp, $pid + $toLog | Out-File -Append -Encoding UTF8 -FilePath $LogPath + } + } + + #Write Content to the EventViewer + If ( $ToEventLog -eq $True ) + { + $LogBaseName = Get-Item $LogPath | Select-Object -ExpandProperty BaseName + Write-EventLog -LogName "Application" -Source $LogBaseName -EventID 3001 -EntryType $Msg.MessageType -Message "$($Msg.Message)" -Category 1 + } + + #Write to screen for debug mode + Write-Debug $MessageToScreen + + #Write to screen for ToScreen mode + If ($ToScreen -eq $True) + { + if ($MessageType -eq "ERROR") + { + Write-Error -Message $MessageToScreen + } + elseif ($MessageType -eq "WARNING") + { + Write-Warning -Message $MessageToScreen + } + else { + Write-Output -Message $MessageToScreen + } + } + + } +} \ No newline at end of file From 18bcc3470c533e4c6c34be345d1bc546ce36fe5b Mon Sep 17 00:00:00 2001 From: timoline Date: Sat, 27 Jul 2019 17:02:51 +0200 Subject: [PATCH 2/2] reverted warning and error output to screen. Its not working like i would --- Module/PSLogging/public/Write-LogEntry.ps1 | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/Module/PSLogging/public/Write-LogEntry.ps1 b/Module/PSLogging/public/Write-LogEntry.ps1 index 2324134..4380ec4 100644 --- a/Module/PSLogging/public/Write-LogEntry.ps1 +++ b/Module/PSLogging/public/Write-LogEntry.ps1 @@ -136,17 +136,9 @@ Function Write-LogEntry #Write to screen for ToScreen mode If ($ToScreen -eq $True) { - if ($MessageType -eq "ERROR") - { - Write-Error -Message $MessageToScreen - } - elseif ($MessageType -eq "WARNING") - { - Write-Warning -Message $MessageToScreen - } - else { - Write-Output -Message $MessageToScreen - } + + Write-Output -Message $MessageToScreen + } }