Tuesday 23 December 2008

Get-FileCount.ps1

  1. # Get-FileCount.ps1 
  2. # Uses shell.application to get a count of files in a folder 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # First get shell object 
  6. $Shell = new-object -com Shell.Application 
  7.  
  8. # Now get folder details and item counts for a folder 
  9. $foldername = "D:\Foo" 
  10. $folder = $shell.namespace($foldername
  11. if (!$folder) { 
  12. "Folder: {0} does not exist" -f $foldername 
  13. return 
  14.  
  15. # Now output the count of folders 
  16. if ($folder) {  
  17.  $folderitems = $folder.items()  
  18.  $count = $folderitems.count  
  19.  
  20.  $folderps1items = $folderitems | where {$_.type -eq "PS1 File"
  21.  $countps1items=$folderps1items.count 
  22.   
  23.  "Folder `"{0}`" contains {1} files"     -f $foldername, $count 
  24.  "Folder `"{0}`" contains {1} PS1 files" -f $foldername, $countps1items 

This script produces the following output:

PSH [D:\foo]: .\shell.application\Get-FileCount.PS1'
Folder "D:\Foo" contains 38 files
Folder "D:\Foo" contains 22 PS1 files

6 comments:

Unknown said...

Hi, the above count script is nice but how can we get file numbers from sub directories without give subfolders names, like if we need to get numbers of files of all sub directory of $home\documents.

Thank you.
Gurpreet

Thomas Lee said...

Getting a count of all the files in a folder and below would involve implementing recursion.

See http://pshscripts.blogspot.com/2009/10/get-foldersizeps1.html for an example. You could hack this script to add a count of the files in addition to just adding the size.

Unknown said...

This is a very handy script. Is it possible to add an action if the filecount returns a specific value? i.e if the number of files is greater than 20, then trigger a service restart?

thanks

Thomas Lee said...

Re Jonathan's comment. Sure, it's is definately possible.

:-)

Unknown said...

haha cool- im off to RTFM! PSH noob alert! ;)

Unknown said...

Thanks, this is great. Can you guys advise how i might get the script the allow me to input a folder instead of it being coded in the script. I have mapped folders that i would like to check if anyone has changed using the script. Any help will be apppreciated.