0

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):

  • All dates less than 09/30/2011 (already done with code above)
  • File with date range 09/30 - 10/6
  • File with date range 10/7 - 10/14
  • Etc, etc, until I reach the most recent date

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
   }

1 Comment

mjolinor -- thank you! I'll play around with your code and see if I can get it to work for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.