IntermediateLesson 6 of 16

File System and Process Management

Manage files, directories, and content with Get-ChildItem, Copy-Item, and Set-Content; control Windows services and processes with Start-Service, Stop-Service, and Get-Process; and build operational reports for system administration tasks.

🧒 Simple Explanation (ELI5)

File system management is like having a super-powered file explorer that works from a text command and can apply the same action to thousands of files at once. Process and service management is like Task Manager but scriptable—you can restart a crashed service automatically, kill all instances of a rogue process, or check whether a critical service is running on 50 servers in 10 seconds.

🔧 Why Do We Need It?

⚙️ Technical Explanation

PowerShell exposes the file system through the FileSystem provider. All file and directory cmdlets work through this provider, which is why Get-ChildItem, Copy-Item, and Remove-Item work identically on files, the registry, and certificate stores—just at different paths (C:\, HKLM:\, Cert:\).

Services are managed with Get-Service, Start-Service, Stop-Service, Restart-Service, and Set-Service. For deeper service details (start account, path, dependencies), use Get-CimInstance Win32_Service instead, which returns richer objects.

Processes are managed with Get-Process, Start-Process, Stop-Process, and Wait-Process. Use -Id for precise targeting, -Name for name-based discovery. Prefer Stop-Process over Stop-Process -Force because -Force sends SIGKILL with no graceful shutdown.

⚠️
Always Use -WhatIf Before Remove-Item -Recurse

Running Remove-Item -Path C:\Logs -Recurse -Force is irreversible. Always run it first with -WhatIf to see exactly what will be deleted. In scripts, consider adding -Confirm for first-run validation. Production deployments that clean up old artifacts should use a whitelist (only delete files matching a pattern) rather than a blacklist (delete everything that is old).

📂
Test-Path Before Every File Operation

Always check whether a path or file exists before piping to Copy-Item, Move-Item, or Remove-Item: if (Test-Path $targetDir) { ... }. Scripts that assume a directory exists will throw terminating errors at a critical moment. Use New-Item -ItemType Directory -Force to ensure a directory exists before writing to it.

📊 Visual Representation

File System Cmdlet Workflow
Get-ChildItem
Filter by age / name
Copy-Item / Remove-Item
Log results

⌨️ Commands / Syntax

powershell
# ===== FILE SYSTEM =====

# List files recursively, filter by extension and age
Get-ChildItem -Path C:\Logs -Recurse -Filter *.log |
  Where-Object LastWriteTime -lt (Get-Date).AddDays(-30)

# Delete old log files (test with -WhatIf first)
Get-ChildItem -Path C:\Logs -Recurse -Filter *.log |
  Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) |
  Remove-Item -WhatIf

# Copy files to a deployment folder, creating destination if needed
$dest = "C:\Deploy\Release"
if (-not (Test-Path $dest)) { New-Item -ItemType Directory -Path $dest | Out-Null }
Copy-Item -Path "C:\Build\*" -Destination $dest -Recurse -Force

# Read and write text
$content = Get-Content -Path C:\Config\app.json -Raw
Set-Content -Path C:\Config\app.json -Value $content.Replace("dev", "prod")

# Append to a log file
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path C:\Logs\deploy.log -Value "[$timestamp] Deployment completed"

# Get file hash for integrity check
Get-FileHash -Path C:\Deploy\app.zip -Algorithm SHA256

# ===== SERVICES =====

# Check service status
Get-Service -Name "wuauserv"

# Restart a service
Restart-Service -Name "wuauserv" -Force

# Find stopped services that should be running
Get-Service | Where-Object { $_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic' }

# Get rich service details (start account, path, dependencies)
Get-CimInstance Win32_Service | Where-Object Name -eq "wuauserv" |
  Select-Object Name, StartName, PathName, State

# ===== PROCESSES =====

# Top 10 CPU-consuming processes
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 |
  Select-Object Name, Id, CPU, WorkingSet

# Stop a process by name (graceful then forced)
Get-Process -Name notepad | Stop-Process

# Kill a specific process by ID
Stop-Process -Id 1234 -Force

# Start a process and wait for it to finish
$proc = Start-Process -FilePath "msiexec.exe" -ArgumentList "/i app.msi /quiet" -Wait -PassThru
Write-Host "Installer exit code: $($proc.ExitCode)"

💼 Example (Real-world Use Case)

A weekly maintenance script runs on 30 application servers. It deletes log files older than 14 days, compresses the current week's logs to a ZIP archive, copies the archive to a storage share, checks whether the App Service worker process is running, and restarts it if it is stopped. The entire task that used to take an engineer 2 hours of RDP sessions now runs in 90 seconds via PowerShell Remoting.

🧪 Hands-on

  1. List all .log files in your TEMP folder: Get-ChildItem -Path $env:TEMP -Filter *.log -Recurse.
  2. Find files older than 7 days and preview deletion with -WhatIf.
  3. Create a test directory and write a test file: New-Item -ItemType Directory C:\PSTest; Set-Content C:\PSTest\test.txt "Hello".
  4. Check the status and start type of the Windows Update service.
  5. List the top 5 processes by memory usage (WorkingSet64).
🎮
Try It Yourself

Write a disk cleanup script: use Get-ChildItem -Path $env:TEMP -Recurse to list all temp files, filter to those older than 30 days with Where-Object LastWriteTime -lt (Get-Date).AddDays(-30), calculate the total size with Measure-Object -Property Length -Sum, print a summary line ("Would free X MB"), and then run the removal with -WhatIf. Only remove the -WhatIf when you are confident the output is correct.

🐛 Debugging Scenario

Problem: a deployment script fails with "Access to the path is denied" when copying build artifacts to the release folder.

🎯 Interview Questions

Beginner

How do you list all files in a directory recursively?

Get-ChildItem -Path C:\Logs -Recurse. Add -Filter *.log to limit to log files. Add Where-Object conditions to filter by age, size, name pattern, etc.

How do you stop and restart a Windows service?

Restart-Service -Name servicename -Force. Or stop then start: Stop-Service -Name servicename; Start-Service -Name servicename. Use Get-Service first to verify the service name.

How do you check if a file or directory exists before working with it?

Use Test-Path: if (Test-Path C:\Logs\app.log) { ... }. Test-Path returns $true if the path exists, $false otherwise. Use it before every file operation to avoid terminating errors on missing paths.

Scenario-based

A deployment script fails because a running process is locking a DLL you need to replace. How do you handle it?

First identify the locking process: use Get-Process or query handle-locking tools. Stop the process gracefully with Stop-Process, replace the DLL, then start the process again with Start-Process. In a CI/CD pipeline, add this stop/start sequence to the pre-deploy and post-deploy stages.

A weekly log cleanup script deleted files it should not have touched. How do you prevent this going forward?

Use a whitelist pattern (only delete .log files matching specific names) instead of broad wildcards. Add -WhatIf output to a log file in the first pass and implement human review before committing the deletion. At minimum, move files to an archive directory first and wait 24 hours before deleting—this allows recovery if something was wrongly targeted.

🌐 Real-world Usage

Platform teams use PowerShell file management scripts in CI/CD post-deploy hooks to clean up staging artifacts and verify deployment file integrity with Get-FileHash. Service management scripts run as scheduled tasks on Windows to ensure critical services like IIS, MSSQL, and custom app services restart automatically after unexpected shutdowns, reducing on-call alert noise.

📝 Summary

Get-ChildItem, Copy-Item, Move-Item, and Remove-Item form the core file system toolkit. Always check with Test-Path first and preview with -WhatIf before any deletion. Manage services with Get-Service, Start-Service, Stop-Service, Restart-Service. Get richer service details with Get-CimInstance Win32_Service. Manage processes with Get-Process and Stop-Process. File hash verification with Get-FileHash ensures artifact integrity in deployment pipelines.