PowerShell Basics: Script to List Files with Examples

PowerShell Basics_ Script to List Files

PowerShell Script to List Files

These examples explain how to get started with PowerShell.  However, I dislike ‘Hello World’ examples, therefore my script has a practical use namely, to get a listing of a particular type of file, in a particular directory tree.

This Week’s Secret

A year ago both Vista and PowerShell seemed like a distant dreams, now they are reality.  Each had its development problems but the final product is a huge improvement on XP and VBScript respectively.  While many commentators do nothing but look for points to criticise, I view the well-documented teething problems as a sign that we are still at an exciting stage of computing.

To amplify what I mean, let us compare improvements in Vista and PowerShell with improvements in my new Ford car.  Is my new car more powerful than the previous model, does it do more MPG, is it more secure, is it more exciting?  Sadly the answers on all points were ‘not really’.  Ask the same questions about Vista or PowerShell and the answers were a resounding, ‘Yes’ for all questions.

My only complaint is that as an IT professional, I foolishly believe that I will soon master the new product.  In reality it takes ages to become expert on a new IT system.  The good news, at least for me, is that learning the new features is exciting and brings out my pioneer spirit.

This Week’s Mission

My pure scripting task is to list all files with a given extension in a particular directory tree.  Specifically, all dlls in the windows\windows32 folder.  This simple mission is much like typing the DOS command: dir \s.

My learning agenda for PowerShell is as follows:
1) To appreciate the rhythm of the PowerShell language.  Verb-noun pairs.
2) To see how easy it is to introduce $variables
3) To employ the power of the pipe command (|) so that the output of the first command becomes the input of a second command.
4) To interrogate the capabilities of an object with get-member.

Example 1 – Find all dlls in the Windows\System32 folder

Pre-requisites

You need to have already installed a local copy of PowerShell RC2.  If necessary search the internet for ‘Microsoft PowerShell download’.  Note PowerShell RC2 is much changed from its predecessor, release candidate 1.

Instructions

    1. Save the following script to a text file with a .ps1 extension, for example: C: \Script\dll.ps1.
    2. Launch PowerShell and navigate to the folder where you saved the .ps1 file.  The cd command works fine.
    3. To call for your script file, type at the command line PS> .\dll.ps1.

Note 1. The rhythm of the command is:  dot slash filename.
Note 2. You don’t have to type PS>

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem C:\windows\system32 -recurse
# $Dir |get-member
$List = $Dir | where {$_.extension -eq ".dll"}
$List | format-table name

Learning Points

Note 1: Beginning a script with cls is one of my idiosyncrasies, it simply means clear the screen of any previous output.  The hash symbol # means a remark, or do not process this line.

Note 2:  $Dir = get-childitem C:\windows\system32 -recurse
This command sets the variable $Dir to the path of the files we seek for our list.  You have probably guessed the purpose of the -recurse switch, to drill down to the sub-folders.  Get-childitem is often abbreviated to its alias gci.

Note 3:  $List = $Dir | where {$_.extension -eq “.dll”}
$List is another variable whose purpose is to filter the output, as a result we get only files with .dll extension.  Pay particular attention to the construction $_. which means, in this pipeline.  Also observe that instead of the equals sign, PowerShell needs -eq.

Note 4:  One of PowerShell’s features is the pipe symbol (|).  Most PowerShell scripts contain at least one pipe to control, or filter the output of the main command.

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

Example 2 – Discover Properties with: Get-member

The purpose of this script is to list the properties of the file object controlled by the $dir variable.  When we display the list, how much information do we want?  What file properties are available?  All is revealed by get-member.

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem C:\windows\system32 -recurse
$Dir |get-member
# $List = $Dir | where {$_.extension -eq ".dll"}
# $List |ft fullname |out-file C:\scripts\dll.txt
# List | format-table name

Learning Points

Note 1:  This is the same script as example 1, all that has changed is the #.  I have ‘remmed’ out the list and activated the line: $Dir |get-member.

Note 2:  Get-member lists the properties and methods of the PowerShell object $Dir.  Once we have our list we can control the output specified by format-table.  See next example.  See more on Get-ChildItem -Filter.

Guy Recommends: SolarWinds Engineer’s Toolset (FREE TRIAL)Engineer's Toolset v10

This Engineer’s Toolset provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset on a 14-day free trial now!

SolarWinds Engineer's Toolset Download 14-day FREE Trial

Example 3 – Output to a file

Seeing the files on screen is fine, but with lists of files, it’s often handy to generate a file containing your script’s output.

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem C:\windows\system32 -recurse
# $Dir |get-member
$List = $Dir | where {$_.extension -eq ".dll"}
$List |ft fullname |out-file C:\Scripts\dll.txt
# List | format-table name

Learning Points

Note 1:  Here is the line that I activated by removing the #. $List |ft fullname |out-file c: \Scripts\dll.txt.  What this does is create a file in the c: \Scripts folder.  (Note it does not create the \Scripts folder itself, you must do that) In that dll.txt file are the names of all the files with a .dll extension.

Note 2:  ft, meaning format-table, is one of the built-in aliases which make the code shorter to write.

Guy’s Challenges

Challenge 1:  Set the script to list a different extension, for example .com or .exe.

Challenge 2:  Persuade the script to output the ‘length’ property of the files.

Challenge 3:  Filter the object property with -MemberType, for example remove unwanted Methods leaving only Property:
$Dir |get-member -MemberType property

Summary of Using PowerShell to List Files

PowerShell is a very efficient scripting language.  In this example we use $variables and verb-noun pairs to create a script which lists the files we seek.  I hope you will tweak my examples to list the types of files that you need.  Moreover, I hope that you can see how to adjust the variable, as a result you can locate a directory tree of your choosing.  As a bonus, Example 3 outputs the list of files, not to screen, but to a text file.

 


See more Microsoft PowerShell file tutorials:

PowerShell Home   • Add-Content   • Get-Content   • Set-Content  • PowerShell -Filter   • Test-Path

PowerShell Get-ChildItem   • Get-ChildItem -Include   • Get-ChildItem -Exclude   • Compare-Object

PowerShell Registry  • Get-Credential  • PowerShell ItemProperty  • PowerShell ItemPropery GCI

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.