How To Output A List Of All Files In A Directory Using PowerShell

PowerShell Logo

The Problem

I was recently tasked with sifting through years of stuff that had built up on one of the Windows servers at work and removing that which was no longer required. As a developer, this largely meant clearing out the local instance of SQL Server (tables, views, stored procs, functions, SSIS packages and jobs), but also there were a lot of batch (.bat) files and SQL (.sql) files knocking about.

These files needed cataloguing before I archived any of them as I knew that some were still in use. SQL Server wasn’t a problem as there are various system stored procedures to return a list of various entities, but how was I going to get a list of files that were scattered and buried in the ageing directory structure?

I tried using the Windows Explorer search function, but it was so hit and miss that I couldn’t rely upon it.

I thought maybe I could knock up an ASP.Net page to trawl through the folders and give me a list. Sure I could do this (I recall doing it with Classic ASP many moons ago), but then I remembered about PowerShell.

PowerShell

I’d only recently heard of PowerShell and seen some script and was impressed with what could be achieved, but I hadn’t had a real reason to use it. Basically, PowerShell is a powerful scripting tool that sits under the Windows GUI and allows the user to perform all sorts of magical tasks. I won’t go into detail here, so take a look at this: What can I do with PowerShell? Surely it could perform some basic file filtering and output the list. I wasn’t wrong.

Get To The Point

This is all you need to do:

Get-ChildItem C:\ -Recurse | Where {$_.extension -eq “.bat”} | ForEach-Object { $_.FullName } > C:\File.txt

Here’s how to paste script into PowerShell.

Break It Down

I’m not going to pretend that I know exactly what the switches do, but here’s a quick breakdown of the script:

  • The script is broken up by the pipes (|)
  • Get-ChildItem C:\ returns all files within the root of C:. The drive letter can be changed
  • -Recurse loops through all of the subdirectories C: and returns the files in those subdirectories too. How simple is that? I love it!
  • Where {$_.extension -eq “.bat”} only returns files with a .bat file extension. You can omit this if you want to return all file types
  • ForEach-Object { $_.FullName } returns the full path of each file, including the drive letter
  • > C:\File.txt chucks the results into a text file with a name and location of your choice. You can omit this to display the output within the PowerShell window instead

Bish, bash, bosh, job done!

 

Photo Credit: Joe Olson via Compfight cc

Leave a Reply

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

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