Bookmark and Share

Hey, Scripting Guy! QuestionHey, Scripting Guy! I have a number of files that I work with based upon the date the file was created. I need an easy way to sort the listing of the files in a folder by creation date if possible. I am not sure this is even possible. When I look at the files in Windows Explorer, the date the file was created does not even appear. When I use the Windows PowerShell Dir command, the creation date does not appear either. Is this something that Windows quit tracking? Or is the date a file was modified the same thing as the date the file was created?

-- JB

Hey, Scripting Guy! Answer

Hello JB,

Microsoft Scripting Guy Ed Wilson here. You know, when I am looking at pictures I took while I was scuba diving off the Little Caymans, such as the one following this paragraph, I often like to look at the creation date of the picture. In this way, I can match it up with the dates in my dive log and always remember where the picture was taken. In fact, because the time is also recorded in the creation date, I know not only where the picture was taken, but also the dive number. From my dive computer, I can look it up and tell you the water temperature, the maximum depth of the dive, the length of time I was in the water, the visibility, and all the other information (including the name of my dive buddy).

Image of sea life off Little Caymans


Anyway, JB, you did not mention why you need to look at the creation date of the file, nor did you say the types of files with which you are working. But in reality, it does not matter. Because the SortFilesInFolderByCreationDate.ps1 script will accept a path argument and a filter argument, you can choose the folder and the file with which to work. The complete SortFilesInFolderByCreationDate.ps1 script is seen here.

SortFilesInFolderByCreationDate.ps1

Param([string]$path, [string]$filter, [switch]$help)

Function Sort-Files ([string]$path,[string]$filter)
{
 Get-ChildItem -Path $path -Filter $filter |
 Sort-Object -Property CreationTime
} #end Sort-Files

Function Get-HelpText
{
 $helpText = @"
DESCRIPTION:
  Sorts files by creation date. Accepts parameter for path and file type.
EXAMPLE:
  SortFilesInFolderByCreationDate.ps1 -path c:\fso -filter "*.txt"
  SortFilesInFolderByCreationDate.ps1 -p c:\fso -f *.txt
  SortFilesInFolderByCreationDate.ps1 c:\fso *.txt
"@
 $helpText
} #end Get-HelpText
# *** Entry point to Script ***

if($help) { Get-HelpText ; exit }
Sort-Files -path $path -filter $filter |
Format-Table -property name, creationtime -AutoSize

The SortFilesInFolderByCreationDate.ps1 Windows PowerShell script begins by creating three command-line parameters. This will allow you to change the directory location or the file type to sort without needing to actually edit the text of the script. The SortFilesInFolderByCreationDate.ps1 script also creates a switched parameter named help that will display a help string when the script is run with the –help switch. The command-line parameter statement is seen here:

Param([string]$path, [string]$filter, [switch]$help)

The main function in the SortFilesInFolderByCreationDate.ps1 script is the Sort-Files function. It accepts the –path parameter and the –filter parameter for inputs. When the parameters for the function are defined, they are specified as strings. To ensure the input is an instance of the system.string .NET Framework class, the class name is placed inside square brackets and it is used to constrain the value of the input parameter. An example of using this technique is shown here, where the number 15 is converted into a string value:

PS C:\> $a = [string]15
PS C:\> $a.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


PS C:\>

Inside the Sort-Files function, the Get-ChildItem cmdlet is used to obtain a listing of all the files in the specified folder that meet the filter criteria. An example of using the Get-ChildItem cmdlet to display a listing of jpg files from the c:\fso folder is seen here:

PS C:\> Get-ChildItem -Path C:\fso -Filter *.jpg


    Directory: C:\fso


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        10/12/2008   7:26 PM    9941280 LittleCayman_0122_edited-1.JPG


PS C:\>

After you have the collection of files that meet the filter criteria, the results are passed across the Windows PowerShell pipeline to the Sort-Object cmdlet. The Sort-Object has several parameters. The first parameter is the –property parameter, which is used to specify which properties will be sorted. The –property parameter will accept multiple properties, but in general its usefulness seems to breakdown after two or three properties to sort on. The other main parameter you will want to use is the –descending switched parameter. By default Windows PowerShell sorts in ascending order. The sorting is done in a case-insensitive fashion unless the –casesensitive switched parameter is used. You also have the ability to use the –unique switched parameter to cause the Sort-Object cmdlet to return only unique values. The use of the Sort-Object cmdlet is illustrated here:

PS C:\> Get-ChildItem -Path C:\fso -Filter *.txt | Sort-Object -Property name -Descen
ding


    Directory: C:\fso


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         9/15/2009   5:30 PM         20 IwasHere.txt
-a---         9/14/2009  12:09 PM          0 8907.txt
-a---         9/14/2009  12:09 PM          0 5678.txt
-a---         9/14/2009  12:09 PM          0 2456.txt
-a---         9/14/2009  12:09 PM          0 1356.txt
-a---         9/14/2009  12:09 PM          0 1345.txt
-a---         9/14/2009  12:09 PM          0 1234.txt


PS C:\>

The complete Sort-Files function is seen here:


Function Sort-Files ([string]$path,[string]$filter)
{
 Get-ChildItem -Path $path -Filter $filter |
 Sort-Object -Property CreationTime
} #end Sort-Files

When a script uses command-line parameters, it is a best practice to implement some kind of Help system for the user of the script to know which parameters are available and what sample syntax might look like. It is important to do this, even if you do not intend to share the script with anyone else. In Windows PowerShell 2.0, you will be able to use the Get-Help cmdlet to provide Help for your script, but in Windows PowerShell 1.0 there is no such feature.

To make your script display Help in a systematic fashion, use the Get-HelpText function. The Get-HelpText function uses a here-string to store the Help text in a variable named $helpText. The here-string begins with the at symbol and quotation mark (@"), and it ends with the quotation mark and the at symbol ("@). Between the tags, everything is interpreted as text. The first advantage of using a here-string is that it allows you to dispense with typing quotation marks at the beginning and end of each line. The second advantage is that it allows you to ignore quoting rules and issues with escaping the quotation marks inside a text string. The use of the back tick (`) symbol to escape a quotation mark inside a string is illustrated here:

PS C:\> "This is a "string" with a quote in it"
Unexpected token 'string with a quote in it' in expression or statement.
At line:1 char:39
+ "This is a "string" with a quote in it" <<<<
PS C:\> "This is a `"string`" with a quote in it"
This is a "string" with a quote in it
PS C:\>

The contents of the here-string are assigned to the $helpText variable in the Get-HelpText variable. The last thing the Get-HelpText function does is to display the contents of the $helpText variable. This is seen here:


Function Get-HelpText
{
 $helpText = @"
DESCRIPTION:
  Sorts files by creation date. Accepts parameter for path and file type.
EXAMPLE:
  SortFilesInFolderByCreationDate.ps1 -path c:\fso -filter "*.txt"
  SortFilesInFolderByCreationDate.ps1 -p c:\fso -f *.txt
  SortFilesInFolderByCreationDate.ps1 c:\fso *.txt
"@
 $helpText
} #end Get-HelpText

The entry point to the script first checks for the existence of the $help variable. If the $help variable is found, it means the script was run with the –help parameter, and the user of the script wishes to see the Help message. The Get-HelpText function is called, and the Help text is displayed. The script is then exited by using the exit statement. This is seen here:

if($help) { Get-HelpText ; exit }

When the script is run with the –help switched parameter, the Help message is displayed on the Windows PowerShell console. This is seen here:

PS C:\> C:\ScriptingGuys\SortFilesInFolderByCreationDate.ps1 -help
DESCRIPTION:
  Sorts files by creation date. Accepts parameter for path and file type.
EXAMPLE:
  SortFilesInFolderByCreationDate.ps1 -path c:\fso -filter *.txt
  SortFilesInFolderByCreationDate.ps1 -p c:\fso -f *.txt
  SortFilesInFolderByCreationDate.ps1 c:\fso *.txt
PS C:\>

If the $help variable is not present, it means the script was not run with the help switched parameter, because the only way the $help variable will exist is if it is supplied from the command line. After checking for the help variable, the script calls the Sort-Files function. The values for the –path and –filter parameters are collected from the Windows PowerShell command line. The results from the Sort-Files function are passed back to the Format-Table cmdlet. The name and the creationtime properties are selected from the System.Io.FileInfo .NET Framework class, and the –autosize parameter is used to tighten up the data that is displayed on the Windows PowerShell command line. This section of the script is shown here:

Sort-Files -path $path -filter $filter |
Format-Table -property name, creationtime -AutoSize

Well JB, that is about all there is to know about using the Get-ChildItem cmdlet and the Sort-Object cmdlet to find the creation date from your files and display a formatted list.

If you want to know exactly what we will be looking at tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to us at scripter@microsoft.com or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys