I'm trying to create a powershell script to copy only the new entries that match a pattern (can be one or multiple lines) from one file to another, every time the script is run. The source file is updated randomly by an application but the request is to copy the last entries every hour.
The solution I'm working on is to take the last entry from previous run stored in a file and the compare with the last entry from the file, and if these don't match, then start copying the new lines after that one. That is the part when I'm stuck, I can't figure it how to indicate that, instead I'm copying the whole content every time.
This is what I got so far:
Write-Host "Declaring the output log file ..... " -ForegroundColor Yellow
$destinationfile = 'C:\file\out\output.log'
Write-Host "Getting the last line of the source file ..... " -ForegroundColor Yellow
$sourcefile = 'C:\app\blade\inputlogs.log'
$sourcefilelastline = Get-Content $originfile | Select-Object -last 1
$sourcefilelastline
Write-Host "Getting the last line of the destination file ..... " -ForegroundColor Yellow
$destinationfilelastline = Get-Content $destinationfile | Select-Object -last 1
$destinationfilelastline
if ($sourcefilelastline -eq $destinationfilelastline){
Write-Host "Skipping the process ..... " -ForegroundColor Yellow
}
else{
Write-Host "Reading the source log file and updating destination file ..... " -ForegroundColor Yellow
$sourcefilecontent = Get-Content -Path $sourcefile | Where-Object { $_ -ne '' } | Select-String -Pattern 'error' -CaseSensitive -SimpleMatch
$sourcefilecontent | Add-Content $destinationfile
}
Any ideas on how to get this done ? Thanks.
Get-content have a switch 'tail' which lets you read the last rows from a file. Per Microsoft own words:
You can use it in your case start from the bottom line and go up until they match.