<

PowerShell Easylog module

Published on
4,513 Points
1,413 Views
1 Endorsement
Last Modified:
Every time you write a script for your company, you'll want to log some or all of the steps that script is performing, whether it's for troubleshooting purposes or for future reference.

Creating proper logging each and every time you write a script can get extremely time-consuming and monotonous, so I've written a little something that will hopefully make logging in PowerShell a less tedious job.

Ladies and gents, I present to you the first version of "Easylog".
 
<#
 .Synopsis
  Provides a one-liner to effectively write into a logfile and/or on screen.
  
 .Description
  Provides a one-liner to effectively write into a logfile and/or on screen. By using the Write-Easylog command, you can decide in which logfile you wish to write, with the option of showing it in the console in a colour of choice.
  
 .Parameter Logname
  The -Logname parameter is a mandatory parameter in which you decide the name for your logfile. Logfiles will be saved as YYYYMMDD_Logname.log in the .\Logs directory.
 
 .Parameter Text
  The -Text parameter is a mandatory paramater in which you decide the body of your logged message. Don't forget to use quotation marks when using spaces or tabs.
  
 .Parameter OnScreen
  The -OnScreen parameter is an optional parameter. When invoked, your message defined in -Text will appear in your console window as well.
 
 .Parameter OnScreenFGColor
  The -OnScreenFGColor parameter is an optional parameter used when -OnScreen is invoked. In this parameter you can define the foregroundcolour of the text shown on screen.
 
 .Parameter OnScreenBGColor
  The -OnScreenBGColor parameter is an optional parameter used when -OnScreen is invoked. In this parameter you can define the backgroundcolour of the text shown on screen.
  
 .Example
  # Write "Hi-de-ho neighbour!" to the file .\Logs\YYYYMMDD_Script.log
  Write-Easylog -Logname Script -Text "Hi-de-ho neighbour!"
 
 .Example
  # Write "Hi-de-ho neighbour!" to the file .\Logs\YYYYMMDD_Script.log and show it in the console window as well.
  Write-Easylog -Logname Script -Text "Hi-de-ho neighbour!" -OnScreen
  
 .Example
  # Write "Hi-de-ho neighbour!" to the file .\Logs\YYYYMMDD_Script.log and show it in the console window as well, with foregroundcolour red.
  Write-Easylog -Logname Script -Text "Hi-de-ho neighbour!" -OnScreen -OnScreenFGColor red

 .Example
  # Write "Hi-de-ho neighbour!" to the file .\Logs\YYYYMMDD_Script.log and show it in the console window as well, with backgroundcolour yellow.
  Write-Easylog -Logname Script -Text "Hi-de-ho neighbour!" -OnScreen -OnScreenBGColor yellow
  
 .Example
  # Write "Hi-de-ho neighbour!" to the file .\Logs\YYYYMMDD_Script.log and show it in the console window as well, with foregroundcolour red and backgroundcolour yellow.
  Write-Easylog -Logname Script -Text "Hi-de-ho neighbour!" -OnScreen -OnScreenFGColor red -OnScreenBGColor yellow
#>

Function Write-Easylog{
	[CmdletBinding()]
	Param(
	[Parameter(Mandatory=$True,Position=1)]
	[string]$Logname,
	[Parameter(Mandatory=$True,Position=2)]
	[string]$Text,
	[switch]$OnScreen,
	[string]$OnScreenFGColor,
	[string]$OnScreenBGColor
	)
	
	Easylog-Timestamp
	($EasylogTimestamp + " | " + $Text) | Out-File -FilePath ($EasylogLogsFolder + "\" + $EasylogLogstamp + $Logname + ".log") -Append
	if ($OnScreen -eq $true){
		if ([string]::IsNullOrEmpty($OnScreenFGColor) -and [string]::IsNullOrEmpty($OnScreenBGColor)){
			Write-Host ($EasylogTimestamp + " | " + $Text)
		}
		Elseif ($OnScreenFGColor -ne $null -and [string]::IsNullOrEmpty($OnScreenBGColor)){
			Write-Host ($EasylogTimestamp + " | " + $Text) -ForegroundColor $OnScreenFGColor
		}
		Elseif ([string]::IsNullOrEmpty($OnScreenFGColor) -and $OnScreenBGColor -ne $null){
			Write-Host ($EasylogTimestamp + " | " + $Text) -BackgroundColor $OnScreenBGColor
		}
		Else{
			Write-Host ($EasylogTimestamp + " | " + $Text) -ForegroundColor $OnScreenFGColor -BackgroundColor $OnScreenBGColor
		}
	}
}

<#
 .Synopsis
  Easy utility to remove old logfiles from your .\Logs folder.
  
 .Description
  Easy utility to remove old logfiles from your .\Logs folder. By using the Remove-Easylog command with any number of days behind it, you effectively remove all logfiles equal to or older than that number of days.
  
 .Parameter DeleteAfterNDays
  The -DeleteAfterNDays parameter defines the number of days a logging should be kept. All logging equal to or older than N days will be deleted.
  
 .Example
  # Delete all logs older than 4 days.
  Remove-Easylog 4
  
 .Example
  # Delete all logs older than 2 weeks.
  Remove-Easylog 14
#>

Function Remove-Easylog{
	[CmdletBinding()]
	Param(
	[Parameter(Mandatory=$True,Position=1)]
	[int]$DeleteAfterNDays
	)
	
	$LogFiles = (Get-ChildItem $EasylogLogsFolder | Where{!$_.PsIsContainer})
    Foreach ($LogFile in $LogFiles){
	    $Check = [Math]::Abs((New-TimeSpan -Start ((Get-Date).ToShortDateString()) -End (($LogFile.lastwritetime).ToShortDateString())).Days)
		    If ($Check -ge $DeleteAfterNDays){
			    Remove-Item -Path ($EasylogLogsFolder + "\$($LogFile)")
		    }
    }
}

Function Easylog-CheckLogsFolder{
$script:EasylogLogsFolder = "$($EasylogScriptPath)\Logs"
[bool]$EasylogLogsFolderCheck = Test-Path $EasylogLogsFolder -PathType Container
	If ($EasylogLogsFolderCheck -ne $true){
		New-Item $EasylogLogsFolder -Type Directory
		Easylog-Timestamp
        $EasylogLogFolderCreated = "Logfile folder does not exist. Creating $($EasylogLogsFolder)."
        Write-Easylog -Logname Errorlog -Text $EasylogLogFolderCreated
	}
}

Function Easylog-Timestamp{
	$script:EasylogTimestamp = Get-Date -Format "dd-MM-yyyy H:mm:ss"
	$script:EasylogLogstamp = Get-Date -Format "yyyyMMdd_"
}

$EasylogScriptPath = Split-Path $MyInvocation.MyCommand.Path
Easylog-CheckLogsFolder
Export-ModuleMember -Function Write-Easylog
Export-ModuleMember -Function Remove-Easylog

Open in new window


How do you use this module? Simple.

1. Save this code snippet as "easylog.psm1" in the folder in which you have your own script.
2. In your script, place the following line of code:
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
Import-Module ($Scriptpath + "\Easylog.psm1")

Open in new window

3. You now have access to commands Write-Easylog and Remove-Easylog.

When you use Write-Easylog in your own script, it will save whichever message you want - timestamped - in the logfile your choose in a new folder in your scriptpath named Logs.

Example
I want to write "Hi-de-ho neighbour!" to the logfile .\Logs\YYYYMMDD_Wilson.log
Write-Easylog -Logname Wilson -Text "Hi-de-ho neighbour!"

It's THAT easy.

When you use Remove-Easylog you must specify an N number of days. For example, 14.
Remove-Easylog 14

This will then delete all logfiles in your .\Logs directory older than 14 days!

Questions, suggestions and corrections to this script are very welcome!

-Baz
 
1
Comment
1 Comment
LVL 4

Expert Comment

by:Bob McCoy
While it's an interesting module and I can certainly find use for it, I find it disturbing that you want us to "Save this code snippet as "easylog.psm1" in the folder in which you have your own script."  That just doesn't seem right.  And if I create an EasyLog folder in the standard Windows\System32\WindowsPowerShell\v1.0\Modules folder (where I generally place modules that I want universally available), it wants to create the Logs folder there.  Well that presents some problems when I'm running as a normal (non-admin) user.

The location of the module should be completely decoupled from the location of the log files.  Additionally, you should be able to fully path the log file directory.
0

Featured Post

ON-DEMAND: 10 Easy Ways to Lose a Password

Learn about the methods that hackers use to lift real, working credentials from even the most security-savvy employees in this on-demand webinar. We cover the importance of multi-factor authentication and how these solutions can better protect your business!

Join & Write a Comment

Loops Section Overview
Did you know PowerShell can save you time with SaaS platforms? Simply leverage RESTfulAPIs to build your own PowerShell modules. These will kill repetitive tickets and tabs, using the command Invoke-RestMethod. Tune into this webinar to learn how…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month