The 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username

2011 Scripting Games badge

Summary: Advanced Event 9 in 2011 Scripting Games uses Windows PowerShell to create a file name that is based on the date and the user’s name.

About this event



Date of Event

4/14/2011 12:15 AM

Due Date

4/21/2011 12:15 AM

Event scenario

You need to add a logging routine to a script that runs daily on your workstation. For troubleshooting purposes, you would like to keep all of the log files in a single folder named HSGLogFiles. The exact location of this folder is up to you, but it should be stored on the local machine, and it should be in a location that is accessible to all users of the computer. Because the script runs once per day on a per user basis, the log files should be comprised of the year, month, day, and a logged on user name. You are not worried about concurrent users, or remote users—for the purposes of this scenario assume a single interactive user. If the script runs multiple times for the same user on the same day, do not append or overwrite the original log file (which is created during the first run of the day). In other words, if a file exists, the script should exit gracefully and silently. When you create the file, create it silently by not displaying return information to the Windows PowerShell console. An example of such a log file directory is shown in the following image.

Image of directory

Design points

  • For the purposes of this scenario, you can create the HSGLogFiles directory manually.
  • Extra points for automatically creating the HSGLogFiles directory.
  • Extra points for detecting if the HSGLogFiles directory exists. If it does not exist, extra points for creating it. If it does exist, extra points for allowing the script to respond gracefully.
  • Extra points for creating the HSGLogFiles directory in the current user’s MyDocuments folder instead of creating it off of the root.

2011 Scripting Games links

2011 Scripting Games: All Links on One Page

Submit your scripts on PoshCode

Support our Sponsors!

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at, or post your questions on the Official Scripting Guys Forum. Good luck as you compete in this year’s Scripting Games. We wish you well.

Ed Wilson, Microsoft Scripting Guy