I have a powershell script that creates a log file in a network share and then writes on it (also mapping network drives) whenever the user logs in, it’s deployed by GPO. I created two functions to create the log and to write on it, here they are:
# Generates the log
Function New-Log{
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Path,
[Parameter(Position=1)]
[string]$Folder=$null,
[Parameter(Mandatory=$true,Position=2)]
[string]$Name,
[Parameter(Position=3)]
[switch]$OverWrite,
[Parameter(Position=4)]
[switch]$UseDate,
[Parameter(Position=5)]
[int]$MaxDays = 0
)
# New folder (Yes/No)
if($Folder){
$logPath = Join-Path -ChildPath $Folder -Path $Path
}
else{
$logPath = $Path
}
# Add date to log name (Yes/No)
if($UseDate.IsPresent){
$logFile = "$(Get-Date -Format 'dd-MM_HH.mm.ss')_$($Name).log"
}
else{
$logFile = "$Name.log"
}
# Ovewrite existing log
if($OverWrite.IsPresent){
$logFinal = (New-Item -Path $logPath -ItemType File -Name $logFile -Force).FullName
}
else{
if(Test-Path -Path "$logPath$logFile"){
$logFinal = "$logPath$logFile"
}
else{
$logFinal = (New-Item -Path $logPath -ItemType File -Name $logFile -Force).FullName
}
}
# Deletion after a quantity of days
if($MaxDays -gt 0){
if((Get-ChildItem -Path $logPath | Measure-Object).Count -gt $MaxDays){
(Get-ChildItem -Path $logPath | Sort-Object LastWriteTime -Descending | Select-Object -Last 1).FullName | Remove-Item -Force
}
}
return $logFinal
}
# Add log events
Function New-LogEvent{
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$File,
[Parameter(Mandatory=$true,Position=1)]
[string]$Event,
[switch]$UseSemicolon
)
$FLG = Get-Date -Format 'dd/MM/yyyy-HH:mm:ss'
if($UseSemicolon.IsPresent){
Add-Content $File -Value "$FLG; $Event"
}
else{
Add-Content $File -Value "$FLG - $Event"
}
}
The log is created without using OverWrite and UseDate switches.
The problem is that when I look at the log, the older entries get deleted as new entries are written. We have more than 3000 users, so there’s lots of new entries everyday, but for usage measurement purposes boss wants all in the same log. I still don’t know if it’s the functions fault or something related to the .log file extension or even network share permissons. The network share where the log is stored has write/read permissons for all domain users.
Do you guys know any trick on how to keep the log growing permanently?
Thanks in advance!