Cyber Intelligence
Production-Ready Scripts · Reliability

L6. Files, Error Handling, and Debugging

Work safely with the filesystem, understand terminating vs non-terminating errors, and use try/catch/finally, -ErrorAction, and debugging habits that prevent destructive mistakes.

Filesystem Basics

PowerShell uses providers. The filesystem is one provider, but registry, certificate, and variable drives can appear through similar commands.

Get-Location
Get-ChildItem -Path . -File
New-Item -ItemType Directory -Path .\lab
Copy-Item .\input.txt .\lab\input-copy.txt
Remove-Item .\lab\input-copy.txt -WhatIf
-WhatIf is one of the most important safety habits in PowerShell. Use it before commands that change or delete resources.

Error Types

PowerShell has terminating and non-terminating errors. Many cmdlets report a non-terminating error and continue. To catch those errors in try/catch, use -ErrorAction Stop.

try {
  Get-Item -Path .\missing.txt -ErrorAction Stop
} catch {
  [pscustomobject]@{
    Message = $_.Exception.Message
    Category = $_.CategoryInfo.Category
  }
} finally {
  'Cleanup or final logging goes here'
}

Debugging Habits

  • Use Set-StrictMode -Version Latest in scripts while learning.
  • Use Write-Verbose for optional diagnostic messages.
  • Use $PSStyle.OutputRendering = 'PlainText' when clean logs matter.
  • Build scripts in small tested sections.
  • Prefer Join-Path over string-concatenating file paths.

Lab

  1. Create a directory named ps-lab.
  2. Create three text files inside it.
  3. Write a script that counts files and catches missing-path errors.
  4. Run destructive commands first with -WhatIf.
  5. Add Write-Verbose messages and test with -Verbose.
Exam Focus Points
  • Use -WhatIf before commands that modify or delete resources
  • Use -ErrorAction Stop to convert many non-terminating cmdlet errors into catchable errors
  • try/catch/finally is the standard structure for recoverable failures
  • Join-Path is safer than manually concatenating paths
  • Verbose messages help debugging without polluting structured output
Knowledge Check

1. Why might a catch block not run for a cmdlet error?

2. What is the purpose of -WhatIf?

Recommended: Pluralsight

This free course covers the theory. Pluralsight adds structured video courses, hands-on Azure labs, and timed practice exams to make it stick before exam day.

Start AZ-500 prep free10-day free trial available