Powershell script to find files recursively and export to CSV

The following script takes 3 input’s the directory to start searching from, the file extesion we are searching for (eg. .xml) and the file name to output the results as CSV to. If a result file isn’t supplied then the results are dumped to the screen.

The most interesting part of this script is this @{Name=”MB”;expression={“{0:N2}” -f ($_.Length / 1MB)} which allows you to take a property from an object and effectively create a new object. Excellent for modify the format and name of the displayed property. 

if ($args.Length -lt 2){
 Write-Host "Script: findall.ps1" -foregroundcolor yellow
 Write-Host "Usage: findall.ps1 <path> <extension> <output>" -foregroundcolor yellow
 Write-Host "findall will find all files recursively from <path>"
 Write-Host "which have this <extension>. The results are"
 Write-Host "exported to csv file <output> or if <output> isn't"
 Write-Host "provided the results are dumped to the screen"
else {
 $Dir = get-childitem $args[0] -recurse
 $extension = $args[1]
 $List = $Dir | where {$_.extension -eq "$extension"}
 if ($args.Length -eq 3){
  $List | select-object @{Name="Directory";expression={$_.Directory}},@{Name="Name";expression={$_.Name}},@{Name="MB";expression={"{0:N2}" -f ($_.Length / 1MB)}}| Export-Csv $args[2] -NoType
 } else {
  $dirarg = $args[0]

  Write-Host "Results for search of $dirarg looking for $extension files:"
  $List | ft @{label="Directory";expression={$_.Directory}},@{label="Name";expression={$_.Name}},@{label="MB";expression={"{0:N2}" -f ($_.Length / 1MB)}}
Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks

Leave a Reply

Your email address will not be published. Required fields are marked *