@@ -14,6 +14,8 @@ Message that should be printed
14
14
Path to the logfile, should end with .txt or .log
15
15
. PARAMETER AndTerminal
16
16
If provided, will also print the formatted log entry to current execution host instance.
17
+ . PARAMETER DateFormat
18
+ Determines the format for the DateTime stamp to be output in. Default value is dd/MM/yyyy HH:mm:ss
17
19
. EXAMPLE
18
20
Write-Log -Level ERROR -Message "Cannot find the file you specified" -LogFile C:\Logs\log.txt
19
21
Will write the message to the logfile provided
@@ -22,10 +24,13 @@ Will write the message to the logfile provided
22
24
Write-Log -Message "Starting Foo..." -LogFile C:\Logs\FooLog.log -AndTerminal
23
25
Will write "<timestamp> [INFO] Starting Foo..." to logfile specified and also to screen.
24
26
27
+ . EXAMPLE
28
+ Write-Log -Message "Starting Foo..." -LogFile C:\Logs\FooLog.txt -DateFormat "yyyy-MM-dd"
29
+ Will write <timestamp> [INFO] Starting Foo... to logfile specified, where <timestamp> will be in stated format
30
+
25
31
. NOTES
26
32
Work in progress, can definitly be improved...
27
- 1. Add ability to recieve input from pipe, in order to support redirecting to well formed log
28
- 2. Invoke some checking to ensure that the logfile is in .txt or .log format
33
+ 1. Add ability to recieve input from pipe, in order to support redirecting to well formed log
29
34
#>
30
35
function Write-Log {
31
36
param (
@@ -37,22 +42,28 @@ function Write-Log {
37
42
[string ] $Message ,
38
43
39
44
[Parameter (Mandatory = $true )]
40
- [string ] $Logfile ,
45
+ [ValidateScript ({
46
+ if (-not ($_ | Test-Path )){ throw " File does not exist." }
47
+ if (-not ($_ | Test-Path - PathType Leaf)){throw ' The path argument must of a file. Folder paths are not allowed.' }
48
+ if ($_ -notmatch " (\.log|\.txt)" ){throw new ' The file specified in the path must be either of type .log or .txt' }
49
+ return $true
50
+ })]
51
+ [System.IO.FileInfo ] $Logfile ,
52
+ [switch ] $AndTerminal ,
41
53
42
- [switch ] $AndTerminal
54
+ [string ] $DateFormat = " dd/MM/yyyy HH:mm:ss "
43
55
)
44
56
45
- $timestamp = (Get-Date ).ToString(" dd/MM/yyyy HH:mm:ss " )
57
+ $timestamp = (Get-Date ).ToString($DateFormat )
46
58
$logString = " $timestamp `t [$Level ]`t $Message "
47
59
48
- Out-File - FilePath $Logfile - Append $logString
60
+ $logString | Out-File - FilePath $Logfile - Append
49
61
if ($AndTerminal ){
50
62
switch ($Level ) {
51
63
" WARN" { Write-Host $logString - ForegroundColor DarkYellow }
52
64
{$_ -in " ERROR" , " FATAL" } {Write-Host $logString - ForegroundColor Red}
53
65
" DEBUG" {Write-Host $logString - ForegroundColor Gray}
54
66
Default {Write-Host $logString }
55
67
}
56
- }
57
-
68
+ }
58
69
}
0 commit comments