Disclaimer
This is my personal blog. The opinions and views I express are my own. The information I provide is on an as-is basis. I make no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this blog and will not be liable for any errors, omissions, or delays in this information or any losses, injuries or damages arising from its use.

Search file structure for a file or file type and put the results in a CSV file (Powershell)

*** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK ***

I put this script together to search my SAN for some files we didn’t want taking up space on our device. It’s essentially a re-work of this script (https://www.signalwarrant.com/2012/07/31/search-for-specific-file-extension-powershell/) from a few months ago.

It’s pretty simple to use; once you execute the script in the shell it will prompt you for the directory to search. The directory can be in the form of C:\files or \\server\share, either one will work provided you have the proper permissions to the files.

Next, you will be prompted for the file or file type you want to search for; for example file.txt or for all .txt files use *.txt.

Once the search is complete it will save the results in a CSV file and open the file in excel for you.

Why use this over the built in windows search? I think it’s faster and in my case I needed to weed through the results to see exactly which files I wanted to delete, the CSV file makes that easy.

#  *** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK ***
#
# Author: David Hall, signalwarrant.com
#
# This is a re-work of this script: https://www.signalwarrant.com/2012/07/31/search-for-specific-file-extension-powershell/
# with some added functionality
#
# Description:
# This script will search a folder and all folders and files below it for
# a specific file or file type.
#

#This is what Directory you want to search
$searchDir = Read-Host "Directory to search ex. c:\files"

#This is what file or file type(s) you're searching for
$searchFile = Read-Host "File or file type you're searching for ex. file.txt or *.mp3"

#This is the location of your logfile of results if you choose to 
#have the results written to the logfile (uncomment the line below)
$outputDir = "C:\scripts\files_$(get-date -f yyyy-MM-dd).csv"

$files = Get-ChildItem -Path $searchDir -Recurse -Filter $searchFile -EA silentlyContinue | Select Fullname, @{Name="MegaBytes"; Expression={"{0:F2}" -f ($_.Length / 1MB)}}, CreationTime, LastAccessTime | Sort-Object MegaBytes -Descending

#The results output to a CSV file
$files | Export-Csv $outputDir

write-host -foregroundcolor yellow "Search complete, results can be viewed here: $outputDir"

#Start excel and open the logfile of the results
Start-Process Excel -ArgumentList $outputDir

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.