Skip to main content

Get the Files in a Directory in Windows PowerShell

Problem

You want to get or list the files in a directory.

Solution

To retrieve the list of files in a directory, use the GetChildItem cmdlet. To get a specific item, use the GetItem cmdlet:

  • To list all items in the current directory, use the GetChildItem cmdlet: GetChildItem
  • To list all items that match a wildcard, supply a wildcard to the GetChildItem cmdlet:

GetChildItem *.txt

  •  
    • To list all files that match a wildcard in the current directory (and all its chil
    • dren), use the –Include and –Recurse parameters of the GetChildItem cmdlet: GetChildItem –Include *.txt Recurse
  • To list all directories in the current directory, use the WhereObject cmdlet to test

the PsIsContainer property: GetChildItem | Where { $_.PsIsContainer }

• To get information about a specific item, use the GetItem cmdlet: GetItem test.txt

Discussion

Although most commonly used on the filesystem, the GetChildItem and GetItem cmdlets in fact work against any items in any of the PowerShell drives. In addition to

A: through Z: (the standard file system drives), they also work on Alias:, Cert:, Env:, Function:, HKLM:, HKCU:, and Variable:.

One example lists files that match a wildcard in a directory and all its children. That example works on any PowerShell provider. However, PowerShell can retrieve your results more quickly if you use a provider specific filter.

The solution demonstrates some simple wildcard scenarios that the GetChildItem cmdlet supports, but PowerShell in fact enables several more advanced scenarios.

In the filesystem, these cmdlets return objects from the .NET Framework that represent files and directories—instances of the System.IO.FileInfo and System.IO. DirectoryInfo classes, respectively. Each provides a great deal of useful information: attributes, modification times, full name, and more. Although the default directory listing exposes a lot of information, PowerShell provides even more.

If you need dedicated infrastructure for retrieving files and directories with Windows PowerShell, consider a Spain Dedicated Server for greater control over file management, directory operations, PowerShell automation, system administration, and Windows-based application workloads.

Help Category