Skip to content

Commit 18b0a96

Browse files
committed
Write-Log : Out-File error repaired closes #1
1 parent 1ce0267 commit 18b0a96

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

CommonFunctions/Public/Write-Log.ps1

+19-8
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ Message that should be printed
1414
Path to the logfile, should end with .txt or .log
1515
.PARAMETER AndTerminal
1616
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
1719
.EXAMPLE
1820
Write-Log -Level ERROR -Message "Cannot find the file you specified" -LogFile C:\Logs\log.txt
1921
Will write the message to the logfile provided
@@ -22,10 +24,13 @@ Will write the message to the logfile provided
2224
Write-Log -Message "Starting Foo..." -LogFile C:\Logs\FooLog.log -AndTerminal
2325
Will write "<timestamp> [INFO] Starting Foo..." to logfile specified and also to screen.
2426
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+
2531
.NOTES
2632
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
2934
#>
3035
function Write-Log {
3136
param (
@@ -37,22 +42,28 @@ function Write-Log {
3742
[string] $Message,
3843

3944
[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,
4153

42-
[switch] $AndTerminal
54+
[string] $DateFormat = "dd/MM/yyyy HH:mm:ss"
4355
)
4456

45-
$timestamp = (Get-Date).ToString("dd/MM/yyyy HH:mm:ss")
57+
$timestamp = (Get-Date).ToString($DateFormat)
4658
$logString = "$timestamp `t[$Level]`t$Message"
4759

48-
Out-File -FilePath $Logfile -Append $logString
60+
$logString | Out-File -FilePath $Logfile -Append
4961
if($AndTerminal){
5062
switch ($Level) {
5163
"WARN" { Write-Host $logString -ForegroundColor DarkYellow }
5264
{$_ -in "ERROR", "FATAL"} {Write-Host $logString -ForegroundColor Red}
5365
"DEBUG" {Write-Host $logString -ForegroundColor Gray}
5466
Default {Write-Host $logString}
5567
}
56-
}
57-
68+
}
5869
}

0 commit comments

Comments
 (0)