You're over-complicating things.
You're comparing dates in your
Where-Object
filter, so you don't need to transform your reference dates to strings. Just use dates:$prevcheck = Get-Date "2013-06-24 19:27:14" $currenttd = Get-Date
You can use a regular expression to extract the date from the file name and transform it into the desired format:
$filedate = $file.BaseName -replace '^.*(\d{4})(\d{2})(\d{2})$', '$1-$2-$3'
Your regular expression for matching the time is overly correct. Use
^(\d{2}:\d{2}:\d{2})
instead. It's a little sloppier, but it will most likely suffice and is a lot easier on the eye.To prepend the time-match with the date, use
"$filedate `$1"
. The double quotes will cause$filedate
to be expanded to the date from the file name, and the escaped$
(``$1`) will keep the grouped match (see Richard's explanation).While you can assign the results from each step to variables, it'd be simpler to just use a single pipeline.
Try this:
$Logpath = "o:\Log"
$Logfile = "$Logpath\test.txt"
$prevcheck = Get-Date "2013-06-24 19:27:14"
$currenttd = Get-Date
If (Test-Path -LiteralPath $Logfile) { Remove-Item $Logfile }
Get-ChildItem "$LogPath\*.log" | ? {
-not $_.PSIsContainer -and
$_.LastWriteTime -ge $prevcheck -and
$_.LastWriteTime -le $currenttd
} | % {
$filedate = $_.BaseName -replace '^.*(\d{4})(\d{2})(\d{2})$', '$1-$2-$3'
Get-Content $_ | % {
$_ -replace '^(\d{2}:\d{2}:\d{2})', "$filedate `$1"
} | Out-File -Append $Logfile
}