PowerShell: Files and Directories

Many times we feel the need to get the list of files in a directory with all the file details. A picture (screenshot) is worth a thousand words (pixels) but at times it is not the best thing.

(1) Get the file list

Command: DIR

This will give us the list, nothing unusual.

(2) Send the list to a text file

Command: DIR > C:\FileList.txt

The file “FileList.txt” will contain the same text that was shown on console

(3) Get only the files or only directory list

The list contains both the directories and files, how do we get only the files? (we can’t do this in a explorer)

The output of DIR is sent to where{}, the “\$_” is the current item, Attributes is a property, “-ne” means “not equal to”. Each item in the output of DIR is checked for having the “Directory” attribute. Fantastic!

To get only the directories – we change “-ne” to ‘-eq”

(4) Sort by size

So now we have “file only” list, let’s sort by size. This would be useful in next step.

”Length” is a column in the output, which is also a property in each item.

(5) Get only top 5

Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where {\$_.Attributes -ne "Directory"} | sort-object Length | select-object -first 5

(6) Get only the name of file

There is an extra Mode column in the output, let’s get only the Name and Length.

Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where {\$_.Attributes -ne "Directory"} | sort-object Length | select-object -first 10 | select-Object Name, Length

(7) Save the list as .CSV file

It would be interesting to store the output as CSV file to open it in Excel.

Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where {\$_.Attributes -ne "Directory"} | sort-object Length | select-object -first 10 | select-Object Name, Length | Export-csv c:\filelist.csv