September 30, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

An Introduction To PowerShell

  • April 30, 2007
  • By Josh Fitzgerald
  • Send Email »
  • More Articles »

DIR.PS1: The File/Folder Listing

Now, you are ready to display the contents, and their properties, of this folder. The first thing you will do is call the PowerShell Get-ChildItem command with the folder name passed into the script as a parameter. The Get-ChildItem command will get the collection of file and folder objects, not just names, and then pipe those objects directly into the Sort-Object command to sort them. By default, the Sort-Object command will sort based on the Name property of the objects, so you do not need to specify any additional parameters. The sorted collection of objects will then be stored in the variable named $items.

$items = Get-ChildItem $args[0] | Sort-Object

Once you have a collection of file and folder objects, you need to loop through them and display the appropriate properties. To loop through the objects, you use the ForEach command. For each file or folder in your $items collection, you will get the last modified date and time, the name, and the length or size file. The strange looking strings inside the curly brackets are .NET string formatting codes. I use them to easily right- or left-align fields and format dates, times, and numbers. Understanding the string formatting code is not crucial to understanding this script.

The If statement is where you determine if an item is a directory. If the first character of the Mode property equals "d", the item is a directory. You need to check because what you write to the screen for directories is different than what you write for files.

Notice the $totalDirs++ line inside the If statement. It is the counter that keeps track of the number of directories in this directory. Similarly, there is a $totalFiles variable that is used to track the number of files and a $totalSize variable that tracks the total size of all of the files. These values are computed now, but you will not display them until the end of the file listing.

ForEach ($i In $items)
{
   $date = "{0, -20:MM/dd/yyyy  hh:mm tt}" -f $i.LastWriteTime
   $file = $i.Name
   If ($i.Mode.SubString(0, 1) -eq "d")
   {
      $totalDirs++
      $list = $date + "    {0, -15}" -f "<DIR>" 
                 + " " + $file
   }
   Else
   {
      $totalFiles++
      $size = "{0, 18:N0}" -f $i.Length
      $list = $date + $size + " " + $file
   }
   $totalSize += $i.Length
   Write-Host $list
}

Figure 4 shows the output of the script of the updated script.



Click here for a larger image.

DIR.PS1: The Footer

The only thing left to do is write to the screen the total count of files and directories, the total size of the files, and the available free space on this drive. To do this, you will utilize the counter variables ($totalFiles, $totalDirs, $totalSize) that you created in the previous section of the script and you can get the available free space from the $volInfo variable that you created back at the beginning of the script.

Write-Host ("{0, 16:N0}" -f $totalFiles + " File(s)" + `
            "{0, 15:N0}" -f $totalSize + " bytes")
Write-Host ("{0, 16:N0}" -f $totalDirs + " Dir(s)" + `
            "{0, 16:N0}" -f $volInfo.FreeSpace + " bytes free`n")

Figure 5 shows the complete output of the script.



Click here for a larger image.

Caveats and Possible Improvements

Although the script you created produces nearly identical output to the CMD.EXE DIR command, there are a few caveats to be aware of and some possible improvements you could make.

  • This script does not perform any error checking.
  • If a valid path is not passed into the script, the script will fail with a PowerShell error message.
  • The directory count displayed by the script is 2 less than the CMD.EXE DIR command because the Get-ChildItem command does not include the "." and the ".." directories like the CMD.EXE DIR does.
  • Your script sorts by file/folder name by default and does not offer any way to sort by any other attribute.
  • Your script does not have the ability to display the contents for a folder and all of the sub-folders.

Conclusion

Although PowerShell is a powerful shell and scripting language, it can take a little time to really grasp it, especially if you are not already familiar with the .NET Framework. I hope that this article and script will be useful to anyone trying to learn about PowerShell. Even though the script that you created is fairly simple, I believe it can serve as a good foundation for building upon.

About the Author

Josh Fitzgerald is an applications development group leader for a large medical device company in Warsaw, Indiana. Designing and developing Visual Basic .NET applications is only one of his responsibilities, but it is his favorite part of his job. You can reach Josh at josh.fitzgerald@gmail.com





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel