PowerShell: Working with Directories

By Xah Lee. Date: . Last updated: .

Command names and parameter names are case-insensitive.

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 | foreach { $_.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

Create New Directory

mkdir dirName

Note: mkdir is a builtin function, not a cmdlet, not alias. [see PowerShell: What is Cmdlet]

Full syntax to make a directory:

ni dirName -ItemType directory
# dirName can be name or full path

Hide the output:

mkdir dirName | out-null

out-null suppress the useless info about the fact you created a directory.

More efficient way to hide output:

$null = mkdir dirName

Copy Directory

cp c:/Users/john/abc/ f:/backup/ -Recurse
# copy dir's content
cp c:/Users/john/abc/* f:/backup/ -Recurse

Delete Directory

# delete a dir
rm .\dirName
# PowerShell may prompt to confirm
# delete a directory, force, no ask
rm .\dirName -Force -Recurse

If you cannot delete a dir because read only etc, see PowerShell: Get/Set File Attributes

List Empty Directories

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

Delete Empty Directories

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

Current Directory Size

size of current dir and file count:

(dir -File -Recurse | measure -Property Length -sum).sum

How this works: dir -File -Recurse returns System.IO.FileInfo object, which has a property Length. measure sums up that property's values, and return a object with property name sum. The .sum gets the value of property name sum.

Size of current dir in mebibytes:

"{0:N0}" -f ((dir -File -Recurse | measure -Property Length -sum).sum / 1MB)

For gibibytes, use 1GB instead of 1MB.

show sizes of subdirs

# show sizes of subdirs

dir -Directory | foreach { Write-Host $_.name " " -NoNewLine; "{0:N0}" -f ((dir $_ -File -Recurse | measure -Property Length -sum).sum / 1mb); }

PowerShell

How-to

Advanced

Script Examples