PSPowerShell · Lesson 6 of 8

Files & the Filesystem

PowerShell's file cmdlets are powerful and consistent. They work with local files, network paths, and even registry keys using the same commands.

PowerShell
# Navigation
Set-Location C:UsersAlice        # cd equivalent
Push-Location C:Temp              # push to location stack
Pop-Location                       # return to previous location
Get-Location                       # pwd equivalent

# List files
Get-ChildItem                      # ls/dir
Get-ChildItem -File                # files only
Get-ChildItem -Directory           # directories only
Get-ChildItem -Recurse -Filter "*.ps1"  # recursive
Get-ChildItem -Hidden              # show hidden files

# Read/write files
$content = Get-Content "file.txt"              # array of lines
$content = Get-Content "file.txt" -Raw         # single string
Set-Content "file.txt" "Hello, World!"         # write (overwrite)
Add-Content "file.txt" "New line"              # append

# Test file existence
Test-Path "C:Tempile.txt"                   # True or False
Test-Path "C:Temp" -PathType Container        # is it a directory?

# Create, copy, move, delete
New-Item -ItemType File "newfile.txt"
New-Item -ItemType Directory "newdir"
Copy-Item "source.txt" "dest.txt"
Copy-Item "sourcedir" "destdir" -Recurse
Move-Item "old.txt" "new.txt"
Remove-Item "file.txt"
Remove-Item "directory" -Recurse -Force        # force delete (no confirm)

# Read JSON
$config = Get-Content "config.json" | ConvertFrom-Json
$config.name                       # access properties
$config.port                       # typed values

# Write JSON
$data = @{ name = "Alice"; age = 30 }
$data | ConvertTo-Json | Set-Content "output.json"

# CSV
Import-Csv "data.csv"              # returns objects!
$people | Export-Csv "people.csv" -NoTypeInformation