Reputation: 2019
This is in reference to the post here: How to delete date-based lines from files using PowerShell
Using the below code (contributed by 'mjolinor') I can take a monolithic (pipe "|" delimited) CSV file and create a trimmed CSV file with only lines containing dates less than $date
:
$date = '09/29/2011'
foreach ($file in gci *.csv) {
(gc $file) |
? {[datetime]$_.split('|')[1] -lt $date
} | set-content $file
}
The above code works great! What I need to do now is create additional CSV files from the monolithic CSV file with lines containing dates >= $date
, and each file needs to be in 1-week chunks going forward from $date
.
For example, I need the following 'trimmed' CSV files (all created from original CSV):
Upvotes: 0
Views: 784
Reputation: 68273
This is NOT tested with your input (it was adapted from some script I use for time-slicing and counting Windows log events), but should be close to working. It can create files on any arbitrary time span you designate in $span:
$StartString = '09/29/2011'
$inputfile = 'c:\somedir\somefile.csv'
$Span = new-timespan -days 7
$lines = @{}
$TimeBase = [DateTime]::MinValue
$StartTicks = ([datetime]$startString).Ticks
$SpanTicks = $Span.Ticks
get-content $inputfile |
foreach {
$dt = [datetime]$_.split('|')[1]
$Time_Slice = [int][math]::truncate(($dt.Ticks - $StartTicks) / $SpanTicks)
$lines[$Time_Slice] += @($_)
}
$lines.GetEnumerator() |
foreach {
$filename = ([datetime]$StartString + [TimeSpan]::FromTicks($SpanTicks * $_.Name)).tostring("yyyyMMdd") + '.csv'
$_.value | export -csv $filename
}
Upvotes: 2
Reputation: 9678
You can use the GetWeekOfYear
method of Calendar
like this
$date = (Get-Date)
$di = [Globalization.DateTimeFormatInfo]::CurrentInfo
$week = $di.Calendar.GetWeekOfYear($date, $di.CalendarWeekRule, $di.FirstDayOfWeek)
to determine the week number of a given date.
Upvotes: 3