Tuesday, 15 January 2013

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: cd “C:\Program Files\Adobe\Reader 10.0\Reader”
Command: DIR

image 
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)

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

image 
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”
Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where{$_.Attributes -eq "Directory"}

(4) Sort by size

So now we have “file only” list, let’s sort by size. This would be useful in next step.
Command: PS C:\Program Files\Adobe\Reader 10.0\Reader> dir | where {$_.Attributes -ne "Directory"} | sort-object Length

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

 image

(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

image 

(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

No comments:

Post a Comment

Note: only a member of this blog may post a comment.