PowerShell Script to List Files

PowerShell Script to List Files

These examples explain how to start scripting files with PowerShell.  Because I dislike ‘Hello World’ examples, my scripts have a practical purpose, in this instance to get a listing of a particular type of file, in a named directory tree.

 ♣

Our PowerShell Mission Pipe to File

My mission is to list all files with a given extension in a specified directory tree, then write the output to a file.  Specifically, all dlls in the Windows\System32 folder.  This simple task is much like typing the DOS command: dir \s.  What would make my day is if you can alter my script to search for files that interest you.

My learning agenda for PowerShell is as follows:

  1. To appreciate the rhythm of the PowerShell language.  Verb-Noun pairs.
  2. To demonstrate how easy it is to introduce $variables.
  3. To employ the flexibility of PowerShell's pipe command (|) so that the output of the first command, becomes the input of a second command.
  4. To interrogate the properties 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.  If necessary search the internet for 'Microsoft PowerShell download'. 

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.  Incidentally, the Dos command 'cd' (change directory) works fine in PowerShell.
  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
Clear-Host
$Dir = Get-Childitem C:\Windows\System32 -recurse
# $Dir | Get-Member
$List = $Dir | Where-Object {$_.extension -eq ".dll"}
$List | Format-Table name

Learning Points

Note 1: Beginning a script with Clear-Host is one of my idiosyncrasies, it simply means clear the screen of any previous output (just as it does in DOS).  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 that we seek.  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 in this context.

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

Note 5: Out-GridView: PowerShell v 2.0 introduces a new cmdlet to control data display.  See more on how to pipe the results into out-GridView.

Challenge : If the error messages annoy you, append:
-ErrorAction SilentlyContinue  (add the instruction after -recurse)

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 investigate properties and methods
Clear-Host
$Dir = Get-Childitem C:\windows\system32
$Dir |Get-Member

Learning Points

Note 6: This is the same basic script as Example 1, all that has changed is I have appended: $Dir |Get-Member.

Note 7: 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.

Example 3: Pipe 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 pipes output to a file
Clear-Host
$Location = ""
$Output = "C:\Scripts\dll.txt"
$Dir = Get-Childitem C:\Windows\System32 -recurse -ea 4
$List = $Dir | Where-Object {$_.extension -eq ".dll"}
$List | Format-Table Fullname | Out-File $Output
Invoke-Item $Output
# List | Format-Table name

Learning Points

Note 8: 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 yourself.) In that dll.txt file are the names of all the files with a .dll extension.

Note 9: I included Invoke-Item to check the location where the file was created.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor 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 now.

Download a free trial of Solarwinds’ Network Performance Monitor

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

An Alternative Technique: Get-File Function

The idea is to wrap Get-ChildItem in a PowerShell function.  The purpose is to find all program files.

Function Global:Get-File {
Param (
[parameter(mandatory=$false, Position=0)][String]$Name ="*",
[parameter(mandatory=$false)][String]$Extension ="exe",
[parameter(mandatory=$false)][String]$PathAdd,
[parameter(mandatory=$false)][String]$NewLocation
         )
Process {
Clear-Host
"Listing $Name.$Extension files …"
$Prog = "C:\Program Files\"
$Prog86 = "C:\Program Files (x86)\"
$FileFull = $Name +"."+ $Extension
Set-Location $Prog
$Exe1 = Get-ChildItem $FileFull -Recurse
Set-Location $Prog86
$Exe2 = Get-ChildItem $FileFull -Recurse
# End of the core search for files.
# Start of PathAdd and NewLocation logic.
If($PathAdd -ne "") {
"Searching for more $Extension files …"
Set-Location $PathAdd
$Exe3 = Get-ChildItem $FileFull -Recurse -Force -EA SilentlyContinue
      }
ElseIf($NewLocation -ne "") {
Set-Location $NewLocation
"Searching $NewLocation for more $FileFull files …"
$Exe3 = Get-ChildItem $FileFull -Recurse -Force -EA SilentlyContinue
$Exe1 =$Exe2 = $Exe3
       }
#End of file collection
$Exe = $Exe1 + $Exe2 + $Exe3
$Exe | Sort-Object Name -Unique | `
Format-Table Name, @{Label = "Path" ; Expression = {$_.FullName} } -Auto
"The number of $FileFull files is approximately: " + ($Exe.Count -4)
    } #End of Process
}

How to use this function:

Get-File
Get-File -PathAdd D:
Get-File -NewLocation E: -Name S*

See more on creating Get-File Function »

Summary of Using PowerShell to List Files

PowerShell is a very efficient scripting language.  In the examples on this page 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.

If you like this page then please share it with your friends

 


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.