Helpers/LogFile.ps1
function Set-LogFile { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] Param( [Parameter(Mandatory = $true)] [Alias('LogPath')] [string]$Path, [Parameter(Mandatory = $true)] [Alias('Logname')] [string]$Name ) $FullPath = Get-FullPath $Path $Name # Create file if it does not already exists if (!(Test-Path -Path $FullPath)) { # Create file and start logging New-Item -Path $FullPath -ItemType File -Force | Out-Null Add-Content -Path $FullPath -Value "***************************************************************************************************" Add-Content -Path $FullPath -Value " Logfile created at [$([DateTime]::Now)]" Add-Content -Path $FullPath -Value "***************************************************************************************************" Add-Content -Path $FullPath -Value "" Add-Content -Path $FullPath -Value "" } } function Write-LogFile { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [Alias('LogMessage')] [string]$Message, [Parameter(Mandatory = $true)] [Alias('LogPath')] [string]$Path, [Parameter(Mandatory = $true)] [Alias('Logname')] [string]$Name, [ValidateSet("Error", "Warning", "Info")] [string]$Level = "Info" ) Set-LogFile $Path $Name $FullPath = Get-FullPath $Path $Name # Format date for log file $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" switch ($Level) { 'Error' { # Write-Error $Message $LevelText = '[ERROR]:' } 'Warning' { # Write-Warning $Message $LevelText = '[WARNING]:' } 'Info' { # Write-Verbose $Message $LevelText = '[INFO]:' } } Add-Content $FullPath "$FormattedDate $LevelText" Add-Content $FullPath "$Message" Add-Content $FullPath "--------------------------" Add-Content $FullPath "" } function Get-FullPath { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [string]$Path, [Parameter(Mandatory = $true)] [string]$File ) $FullPath = "" if ($Path.Length -gt 0) { if ($Path[$Path.Length - 1] -ne "\") { $FullPath = $Path + "\" + $File } else { $FullPath = $Path + $File } } return $FullPath } |