PowerShell File System Operations
PowerShell provides powerful cmdlets for working with files and directories across different providers.
Basic File Operations
Navigating the File System
# Get current location
Get-Location # or $PWD
# Change directory
Set-Location -Path "C:\Windows" # or cd, chdir
# Get directory contents
Get-ChildItem # or dir, ls
# Filter files by extension
Get-ChildItem -Path "C:\Logs" -Filter "*.log"
Creating Files and Directories
# Create new directory
New-Item -Path "C:\Temp\NewFolder" -ItemType Directory
# Create new file
New-Item -Path "C:\Temp\test.txt" -ItemType File
# Create multiple items
1..5 | ForEach-Object {
New-Item -Path "C:\Temp\File$_.txt" -ItemType File
}
Reading File Content
# Read entire file
Get-Content -Path "C:\Temp\log.txt"
# Read first few lines
Get-Content -Path "C:\Temp\large.log" -TotalCount 10
# Read as raw bytes
[System.IO.File]::ReadAllBytes("C:\Temp\image.jpg")
# Read line by line
foreach ($line in [System.IO.File]::ReadLines("C:\Temp\log.txt")) {
# Process each line
}
File Manipulation
Copying Files
# Simple copy
Copy-Item -Path "C:\Temp\file.txt" -Destination "C:\Backup\"
# Recursive directory copy
Copy-Item -Path "C:\Data\" -Destination "D:\Backup\" -Recurse
# Copy with filtering
Get-ChildItem -Path "C:\Logs\" -Filter "*.log" |
Copy-Item -Destination "E:\Archive\"
Moving and Renaming
# Move file
Move-Item -Path "C:\Temp\old.txt" -Destination "C:\Archive\"
# Rename file
Rename-Item -Path "C:\Temp\file.txt" -NewName "document.txt"
# Bulk rename
Get-ChildItem -Path "C:\Photos\" -Filter "IMG_*.jpg" |
Rename-Item -NewName { $_.Name -replace "IMG_","Vacation_" }
Deleting Files
# Delete single file
Remove-Item -Path "C:\Temp\temp.txt"
# Delete directory (empty)
Remove-Item -Path "C:\Temp\EmptyDir"
# Force delete (recursive)
Remove-Item -Path "C:\Temp\OldData\" -Recurse -Force
# Delete files older than 30 days
Get-ChildItem -Path "C:\Logs\" -File |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
Remove-Item -Force
File Properties and Attributes
# Get file info
$file = Get-Item -Path "C:\Windows\explorer.exe"
$file.Length # Size in bytes
$file.LastWriteTime
$file.Attributes
# Set file attributes
Set-ItemProperty -Path "C:\Temp\secret.txt" -Name Attributes -Value "Hidden,ReadOnly"
# Get file hashes
Get-FileHash -Path "C:\Temp\installer.exe" -Algorithm SHA256
# Calculate directory size
(Get-ChildItem -Path "C:\Data\" -Recurse |
Measure-Object -Property Length -Sum).Sum / 1MB
Working with Paths
# Join paths safely
Join-Path -Path "C:\Users" -ChildPath "Public"
# Get parent directory
Split-Path -Path "C:\Windows\System32\drivers\etc\hosts"
# Resolve relative paths
Resolve-Path -Path "..\Documents\file.txt"
# Test path existence
Test-Path -Path "C:\Temp\lockfile.tmp"
# Get path components
[System.IO.Path]::GetFileName("C:\Temp\data.txt")
[System.IO.Path]::GetDirectoryName("C:\Temp\data.txt")
[System.IO.Path]::GetExtension("report.pdf")
File Content Manipulation
Writing to Files
# Overwrite file
Set-Content -Path "C:\Temp\log.txt" -Value "New content"
# Append to file
Add-Content -Path "C:\Temp\log.txt" -Value "Additional line"
# Write multiple lines
@("First line", "Second line", "Third line") |
Out-File -FilePath "C:\Temp\output.txt"
# Binary data
[byte[]]$bytes = 0x48,0x65,0x6C,0x6C,0x6F
[System.IO.File]::WriteAllBytes("C:\Temp\binary.dat", $bytes)
Stream Readers/Writers
# Efficient for large files
$reader = [System.IO.StreamReader]::new("C:\Temp\large.log")
while ($line = $reader.ReadLine()) {
# Process each line
}
$reader.Close()
# Using statement (auto-closes)
using ($writer = [System.IO.StreamWriter]::new("C:\Temp\output.log")) {
$writer.WriteLine("Log entry: $(Get-Date)")
}
Working with CSV and JSON
# Export to CSV
Get-Process | Export-Csv -Path "C:\Temp\processes.csv" -NoTypeInformation
# Import from CSV
$data = Import-Csv -Path "C:\Temp\users.csv"
# Convert to/from JSON
$json = Get-Content -Path "C:\Temp\config.json" | ConvertFrom-Json
$json | ConvertTo-Json -Depth 5 | Out-File "C:\Temp\newconfig.json"
Advanced File Operations
File System Watcher
$watcher = [System.IO.FileSystemWatcher]::new("C:\Temp")
$watcher.Filter = "*.txt"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
Register-ObjectEvent -InputObject $watcher -EventName Created -Action {
$path = $Event.SourceEventArgs.FullPath
Write-Host "New file created: $path"
}
Working with ZIP Archives
# Create ZIP
Compress-Archive -Path "C:\Data\*" -DestinationPath "C:\Backup\data.zip"
# Extract ZIP
Expand-Archive -Path "C:\Backup\data.zip" -DestinationPath "C:\Restore\"
# Add to existing ZIP
Compress-Archive -Path "C:\Data\newfile.txt" -Update -DestinationPath "C:\Backup\data.zip"
Working with Alternate Data Streams
# Write to alternate stream
Set-Content -Path "C:\Temp\file.txt:metadata" -Value "Additional info"
# Read from alternate stream
Get-Content -Path "C:\Temp\file.txt:metadata"