PowerShell: Working with Directories

By Xah Lee. Date: . Last updated: .

Create New Directory

mkdir dirName

# full syntax
new-item dirName -ItemType directory

Copy Directory

# copy dir, recurse
Copy-Item -Recurse -Path "c:/Users/john/abc/" -Destination "f:/backup/"

# copy dir's content, recurse
Copy-Item -Recurse -Path "c:/Users/john/abc/*" -Destination "f:/backup/"

Delete Directory

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

List Directory Only (no files)

# list directories only (no file) of current dir
Get-ChildItem -Directory -Recurse

# output path only. don't use this for piping
Get-ChildItem -Directory -Recurse -name

List Empty Directories

Get-ChildItem -Directory -Recurse | Where-Object { ($_.GetFiles().Count -eq 0 ) -and ( $_.GetDirectories().Count -eq 0) } | ForEach-Object { $_.FullName }

Show Directory as Tree

# show dir as tree, dir only

# show dir as tree, include files
tree /f

sample output:

│   ├───chromium
│   └───firefox
│   ├───description
│   ├───img
│   └───screenshots

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

Directory Size

Size of current dir:

# size of current dir in mebibytes, rounded to 2 decimals
"{0:N2}" -f ((Get-ChildItem -Recurse | Measure-Object -Property Length -sum).sum / 1MB)

# sample output: 4,002.51

For gibibytes, use 1GB instead of 1MB.




Script Examples