public/New-LogFile.ps1
FUNCTION New-LogFile { <# .DESCRIPTION Creates a new log file for script logging. .PARAMETER Path Root path to your log folder. .PARAMETER Name Name of the application your logs should be for. .PARAMETER NoDatedPath switch If defined the directory path will not include a dated structure. .OUTPUTS Returns a global variable with log file fullname. $Global:LogFilePath .EXAMPLE PS> New-LogFile -Path 'C:\Logs' -Name 'TEST' -NoDatedPath Creates a new log file at the following location C:\Logs\TEST\TEST-Date.txt .EXAMPLE PS> New-LogFile -Path 'C:\Logs' -Name 'TEST' Creates a new log file at the following location C:\Logs\TEST\2024\09\TEST-Date.txt .EXAMPLE PS> New-LogFile -Path 'C:\Logs' -Name 'TEST' -SubName 'Processed' Creates a new log file at the following location C:\Logs\TEST\Processed\2024\09\TEST-Processed-Date.txt .NOTES Author: Adam Branham Date: 20240919 #> PARAM( [Parameter(Mandatory = $true)] [System.IO.FileInfo]$Path, [Parameter(Mandatory = $true)] [string]$Name, [Parameter(Mandatory = $false)] [string]$SubName, [Parameter(Mandatory = $false)] [switch]$NoDatedPath, [Parameter(Mandatory = $false)] [switch]$Console = $true ) BEGIN { IF (-NOT(Test-Path -Path $Path)) { $null = New-Item -Path $Path -ItemType Directory -Force } $Today = (Get-Date).ToString('yyyyMMdd') } PROCESS { IF ($NoDatedPath -eq $true) { IF ($SubName) { $FilePath = Join-Path -Path $Path -ChildPath "$Name\$SubName\$Name-$SubName-$Today.txt" } ELSE { $FilePath = Join-Path -Path $Path -ChildPath "$Name\$Name-$Today.txt" } } ELSEIF ($NoDatedPath -eq $false) { $DatedPath = (Get-Date).ToString('yyyy\\MM') IF ($SubName) { $FilePath = Join-Path -Path $Path -ChildPath "$Name\$SubName\$DatedPath\$Name-$SubName-$Today.txt" } ELSE { $FilePath = Join-Path -Path $Path -ChildPath "$Name\$DatedPath\$Name-$Today.txt" } } IF (-NOT(Test-Path -Path $FilePath)) { $null = New-Item -Path $FilePath -ItemType File -Force $RunAs = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name Add-Content -Path $FilePath -Value '=======================================' Add-Content -Path $FilePath -Value "File Date: [$Today]" IF ($Name) { Add-Content -Path $FilePath -Value "Log Name: [$Name]" } IF ($SubName) { Add-Content -Path $FilePath -Value "Sub Name: [$SubName]" } Add-Content -Path $FilePath -Value "Server: [$($env:COMPUTERNAME)]" Add-Content -Path $FilePath -Value "RunAs: [$RunAs]" Add-Content -Path $FilePath -Value '=======================================' Add-Content -Path $FilePath -Value '' } } END { Set-Variable -Name 'LogFilePath' -Value $FilePath -Scope 'Global' IF ($Console -eq $true) { Set-Variable -Name 'LogFileConsole' -Value $true -Scope 'Global' } } } |