WriteMyLogs.psm1
############################################# # Author: K Lakshmi VidyaSagar # Email: Sagar.PSM1@Gmail.Com # Version: 1.0 # Purpose: To Maintain logs # Initial creation date: 16-Jan-2017 11:51 PM # Last modified date: 16-Jan-2017 11:51 PM ############################################# function New-WriteLogObject { <# .Synopsis Create a log object instance .DESCRIPTION This command allows you to create a log object which can be given in the command Write-Log. This object contains the information like file directory/name and fully qualified file path. .PARAMETER LogsDirectory The directory where the log file should be created. .PARAMETER Filename_Prefix Specifies the prefix of the file name. For example if you specify the input as "ServerReboot" then the log file name shall be "ServerReboot_16_01_2018_17_22_15.txt" where _16_01_2018_17_22_15 is the date_month_Year_24Hours_Min_seconds .PARAMETER Filename_Prefix To this prameter you can specify the command name which is being utilizied. This input appears in the log file header secion. For an example please navigate to examples section. .EXAMPLE $LogObject = New-WriteLogObject -LogsDirectory $env:TEMP -Filename_Prefix ServerReboot -Calling_Command Start-ServerReboot Once you output the content of the $LogObject you can find something like below. For more information about each prameter please look for help on each parameter. FileName : ServerReboot_16_01_2018_17_22_15.txt FileDirectory : C:\Users\SJyo\AppData\Local\Temp FileFQN : C:\Users\SJyo\AppData\Local\Temp\ServerReboot_16_01_2018_17_22_15.txt .EXAMPLE $LogObject = New-WriteLogObject -LogsDirectory "C:\InvalidPath" -Filename_Prefix ServerReboot -Calling_Command Start-ServerReboot In this example the directory "InvalidPath" doesn't exists in C:\ but when I run the command the script will create a folder and a logfile in it. If the object wasn't created successfully because of any issue(like access denied..etc) then you will get $fase as a return statement from the command. #> Param( [Parameter(Mandatory=$true)][String]$LogsDirectory, [Parameter(Mandatory=$true)][String]$Filename_Prefix, [Parameter(Mandatory=$true)][String]$Calling_Command ) $Start_TimeStamp = ([String](Get-Date (Get-Date).ToUniversalTime() -Format "dd-MM-yyyy HH:mm:ss")+" UTC") if(!(Test-Path $LogsDirectory)) { try { New-Item -ItemType Directory -Path $LogsDirectory -Force | Out-Null } catch { $Err = $_ Write-Error $Err break } } if($?) { if($Filename_Prefix -match "\s") { Write-Warning "Your input for file name contains spaces which will be replaced by an underscore '_'" $Filename_Prefix = $Filename_Prefix -replace "\s","_" } $Filename_Postfix = (Get-Date (Get-Date).ToUniversalTime() -Format "dd_MM_yyyy_HH_mm_ss") $FileName = [String]($Filename_Prefix+"_"+$Filename_Postfix+".txt") $FilePath = Join-Path $LogsDirectory -ChildPath $FileName $WhoWhenWhat = @" ================================================= |Script Started By : $ENV:USERNAME |Script Start Time : $Start_TimeStamp |Command Name : $Calling_Command |Computer Name : $Env:Computername ================================================= "@ } try { New-Item -ItemType File -Path $LogsDirectory -Name $FileName -ea 1| Out-Null } catch { Return $false } if($?) { $WriteLogObject = New-Object PSObject $WriteLogObject | Add-Member -MemberType NoteProperty -Name "FileName" $FileName $WriteLogObject | Add-Member -MemberType NoteProperty -Name "FileDirectory" $LogsDirectory $WriteLogObject | Add-Member -MemberType NoteProperty -Name "FileFQN" $FilePath Add-Content -Value $WhoWhenWhat -Path $FilePath Return $WriteLogObject } } function Write-Log { <# .Synopsis Writes the given information/warning/ Error string input to the log file .DESCRIPTION This command allows you to... 1. Write the provided string to the log file 2. If you wish to display the same text on the screen as well then you can do that too 3. All types of logs are colore coded. For example the Information kind of text will be displayed in Green, warning in yellow and obvisouly the errors are displayed in Red. 4. Every feed to the log file will be timestamped in UTC 5. If you wish to add a command output as well to the log file along with your comments, yes you can. For more practical examples please navigate to -Examples secion. .PARAMETER Message This parameter allows you to input the text which you would like to log .PARAMETER InputObject Get the returned results from the command New-WriteLogObject. Parse this variable as InputObject. For more information please navigate to help system of New-WriteLogObject command. .PARAMETER LogEntryType This parameter accepts only one of the input among ("Information","Warning","Error"). Please specify your message type. .PARAMETER WriteToScreenAsWell If you specify this switch the message will be displayed on the screen as well; this is colore coded. This cmdlet is capable to print to screen even from a child thread as well. .PARAMETER ContentObject When you have some results in otherhand and you wish to log even those results as well then you can input them to this parameter. .EXAMPLE $LogObject = New-WriteLogObject -LogsDirectory $env:TEMP -Filename_Prefix ServerReboot -Calling_Command Start-ServerReboot PS C:\>Write-Log -Message "Trying to connect to the server" -Inputobject $LogObject -LogEntryType Information -WriteToScreenAsWell 16-01-2018 18:02:35 UTC, INF : Trying to connect to the server 1. Before you consume the Write-Log you should have the log object which you can get from New-WriteLogObject command. 2. The log file content looks like this ================================================= |Script Started By : KLakshmiVidyaSagar |Script Start Time : 16-01-2018 18:00:51 UTC |Command Name : Start-ServerReboot |Computer Name : Host1 ================================================= 16-01-2018 18:02:08 UTC, INF : Trying to connect to the server .EXAMPLE Write-Log -Message "The blow are the results of Dns service" -Inputobject $a -LogEntryType Information -WriteToScreenAsWell -ContentObject (Get-Content D:\Desktop\tempfile.txt) 16-01-2018 20:02:35 UTC, INF : The blow are the results of Dns service And the log file look like, ================================================= |Script Started By : KLakshmiVidyaSagar |Script Start Time : 16-01-2018 18:12:49 UTC |Command Name : Start-ServerReboot |Computer Name : Host1 ================================================= 16-01-2018 18:16:25 UTC, INF : The blow are the results of Dns service Name : Dnscache RequiredServices : {nsi, Tdx} CanPauseAndContinue : False CanShutdown : False CanStop : True DisplayName : DNS Client DependentServices : {NcaSvc} MachineName : . ServiceName : Dnscache ServicesDependedOn : {nsi, Tdx} ServiceHandle : Status : Running ServiceType : Win32OwnProcess StartType : Automatic Site : Container : #> Param( [Parameter(Mandatory=$true)][String]$Message, [Parameter(Mandatory=$true)][PSObject]$Inputobject, [Parameter(Mandatory = $true)][ValidateSet("Information","Warning","Error")][String]$LogEntryType, [Switch]$WriteToScreenAsWell, $ContentObject ) BEGIN { if(!(Test-Path $Inputobject.FileFQN)) { Write-Error ("Cannot find the file name "+$Inputobject.FileFQN+" and hence cannot proceed further") break } $Current_ForeGround_Color = [Console]::ForegroundColor } PROCESS { [String]$TimStamp = [String](Get-Date (get-date).ToUniversalTime() -Format "dd-MM-yyyy HH:mm:ss UTC") if($LogEntryType -eq "Information"){ $LogEntryType_Short = "INF" } elseif($LogEntryType -eq "Warning"){ $LogEntryType_Short = "WAR" } else{ $LogEntryType_Short = "ERR" } $Message_ = ($TimStamp+", "+$LogEntryType_Short+" : "+$Message) if($LogEntryType_Short -eq "INF") { if($WriteToScreenAsWell) { [Console]::ForegroundColor = "Green" [Console]::WriteLine($Message_) } } elseif($LogEntryType_Short -eq "WAR") { if($WriteToScreenAsWell) { [Console]::ForegroundColor = "Yellow" [Console]::WriteLine($Message_) } } else { if($WriteToScreenAsWell) { [Console]::ForegroundColor = "Red" [Console]::WriteLine($Message_) } } Add-Content -Value $Message_ -Path $Inputobject.FileFQN } END { if($ContentObject) { Add-Content -Value "`n" -Path $Inputobject.FileFQN Add-Content -Value $ContentObject -Path $Inputobject.FileFQN Add-Content -Value "`n" -Path $Inputobject.FileFQN } [Console]::ForegroundColor = $Current_ForeGround_Color } } |