PowerShell: List Files

By Xah Lee. Date: . Last updated: .

Command names and parameter names are case-insensitive.

List Files

List file in current directory.

dir
# list file of a given path
dir c:/Users/xah/web/

If path contain space, need quote. [see Powershell: Path Tutorial]

Show hidden files

dir -Force

recurse

# list file in current dir, and all subdirs
dir -recurse

Show File Path Only

# list file, show path (as string) relative to current dir
dir -recurse -name
# list file, show full path
dir -recurse | % {$_.fullname}

Show Directory as Tree

# show dir as tree, dir only
tree

# show dir as tree, include files
tree /f

sample output:

├───assets
├───dist
│   ├───chromium
│   └───firefox
├───doc
│   ├───description
│   ├───img
│   └───screenshots

This is a command at C:\Windows\system32\tree.com

List Files by File Name Pattern

by File Name Extension:

dir -recurse -file -include *.jpg

multiple extensions:

dir -recurse -file -include *.jpg,*.jpeg

[see PowerShell: String Wildcards]

Emacs backup files (file name ending in ~):

dir -recurse -file -include *~

Exclude by file name extension:

dir -recurse -file -exclude *.jpg,*.jpeg,*.png,*.gif

Search file name by regex:

# list jpg or png files by regex
dir -recurse -file | ? { $_.name -match "\.jpg|\.png"}

[see PowerShell: String Operators]

List Empty Files

dir -recurse -file | ? {$_.length -eq 0}

List Empty Directories

dir -Directory -Recurse | ? { $_.GetFileSystemInfos().Count -eq 0 } | % { $_.FullName }

Delete Empty Directories

dir -Directory -Recurse | ? { $_.GetFileSystemInfos().Count -eq 0 } | rm

List Only Files, No Directory

dir -file -recurse

List Directory Only

List directories only (no file) of current directory:

dir -Directory -Recurse

Show just path (relative to current dir):

dir -Directory -Recurse -name

Show full path path:

dir -Directory -Recurse | % { $_.fullname }

Count Number of Files

# count number of files in current dir and subdirs
dir -file -recurse | measure
# count number of html files in current dir and subdirs
dir -recurse -include *.html  | measure

List File Creation Time

# list file with creation time
dir | sort CreationTime | Format-Table Name, CreationTime
# list files whose creation date is greater than x
dir | ? { $_.CreationTime -gt [datetime]"2014/05/28" } | sort CreationTime | Format-Table Name, CreationTime

Delete File by Wildcard Pattern

# delete macOS folder preference file
dir -Force -recurse -include .DS_Store | rm -Force
# delete emacs backup. file name ending in ~
dir -recurse -file -include *~ | rm

PowerShell

How-to

Advanced

Script Examples