I have a log file that is generated by a scheduled ps1 script. It was working fine when it was just writing lines to the file, but now when I include some file manipulation it's got some fowled/fouled up format that prevents the execution from operating correctly.
The first two lines of the image below are how I would like to see and process the file, the last two are a sample of how its doing it now.
As a result the deletion of the X for the previous record has no effect:
$bootTime = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
$formBootTime = [Management.ManagementDateTimeConverter]::ToDateTime($bootTime)
$file = Get-Content c:\myUptimeLogFile.txt
$fileMeasure = ($file | Measure-Object)
$numberOfLines = $fileMeasure.Count
$numberOfWords = ($file | Select -Index ($numberOfLines -1) | Measure-Object -Word)
$Line = $file | Select -Index ($numberOfLines -2)
$Line.Split(",")
$wordArray = $Line.Split(",")
$LastLineBT = $wordArray[0]
if ($LastLineBT -eq $formBootTime) {
$unmark = "true"
} else {
$unmark = "false"
}
if($unmark -eq "true") {
$output = "C:\myUptimeLogFile_NEW.txt"
$file[-2] = $file[-2] -replace 'X', ' '
$file | Set-Content $output -Encoding ASCII
Remove-Item -Path "C:\myUptimeLogFile_SBY.txt"
Rename-Item -Path "C:\myUptimeLogFile.txt" -NewName "C:\myUptimeLogFile_SBY.txt"
Rename-Item -Path "C:\myUptimeLogFile_NEW.txt" -NewName "C:\myUptimeLogFile.txt"
}
$uptime = (Get-Date) - $formBootTime
"$formBootTime,$(Get-Date),{0:00},{1:00},{2:00},{3:00},X" -f $uptime.Days,$uptime.Hours,$uptime.Minutes,$uptime.Seconds >> C:\myUptimeLogFile.txt
If the $unmarked
is true that's when the files shuffle and and the format apparently shifts. Until then, the >>
uses the correct format.
As per comments, checking Add-Content
for the final line of the code.
Update - solution:
$newLine = "$formBootTime,$(Get-Date),{0:00},{1:00},{2:00},{3:00},X" -f $uptime.Days,$uptime.Hours,$uptime.Minutes,$uptime.Seconds
Add-Content -Path "C:\TestLog1.txt" -Value $newLine -Encoding "ASCII"