PowerShell One Folder per Week

I have the need to run a daily script job and log the results in a separate file for each week. There are two problems that I need to resolve to completely automate this task. (1) I need to figure out how to handle weeks that span multiple years, and (2) I need to come up with a weekly folder naming scheme that will be valid across multiple years. Here are my initial solutions using PowerShell.

First I want to record as a single week the daily logs that occur during a continuous week that spans the beginning and end of two years. I’ve decided to determine the week based on the first Business Day (Monday) of each contiguous Sunday through Saturday 7-day period. I will not determine a week number of the year, but rather will label each week as “Week of Monday (YYYY-MM-DD).”

Based on my solution to the multi-year week problem, I can now define a simple week folder name scheme for storing corresponding daily log files. I intend to use a format like “Week_of_YYYY-MM-DD.” NOTE that in Computer Systems, formatting file or folder names with an ISO 8601 formatted date allows simple natural sorting to result in order by named date.

Now for a quick PowerShell sample to demonstrate how to manipulate a script date this way.

$d = Get-Date
$monday = $d.AddDays([int][DayOfWeek]::Monday - [int]$d.DayOfWeek)
$folderName = 'Week_of_{0:yyyy-MM-dd}' -f $monday
# Example $folderName for current date of Thursday Nov 17, 2015:
#   Week_of_2015-11-16
# NOTE that PowerShell 2.0 requires the [int] cast for DayOfWeek
#   subtraction, but PowerShell 3.0 does not. Check PS version
#   with $host.Version

Hopefully this example helps inspire your own ideas for weekly file and folder names, or other PowerShell tasks requiring a representation of the current week.


About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in System Administration and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s