日志文件格式备受争议

时间:2019-04-30 19:24:42

标签: powershell

我有一个由计划的ps1脚本生成的日志文件。只是在向文件中写入行时,它运行良好,但是现在,当我包括一些文件操作时,它具有某种不正确/不完整的格式,阻止了执行正常运行。

下图的前两行是我希望如何查看和处理文件,后两行是如何立即执行文件的示例。

enter image description here

因此,删除先前记录的X无效:

$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

enter image description here

如果$unmarked为true,那就是文件重新排列并且格式显然发生了变化。在此之前,>>使用正确的格式。

根据注释,在Add-Content中检查代码的最后一行。

更新-解决方案:

$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"

0 个答案:

没有答案