0
0
PowerShellscripting~30 mins

Terminating vs non-terminating errors in PowerShell - Hands-On Comparison

Choose your learning style9 modes available
Understanding Terminating vs Non-Terminating Errors in PowerShell
📖 Scenario: You are writing a PowerShell script to process a list of files. Sometimes, errors happen when accessing files. You want to see how PowerShell handles different types of errors: terminating and non-terminating.
🎯 Goal: Learn how to create commands that produce terminating and non-terminating errors, and how to catch and display these errors in PowerShell.
📋 What You'll Learn
Create a list of file paths including one that does not exist
Set a variable to control error action preference
Write commands that cause terminating and non-terminating errors
Display error messages to understand the difference
💡 Why This Matters
🌍 Real World
In real scripts, handling errors properly helps keep automation running smoothly without stopping unexpectedly.
💼 Career
Understanding error types and handling is essential for system administrators and automation engineers to write reliable PowerShell scripts.
Progress0 / 4 steps
1
Create a list of file paths
Create a variable called filePaths that contains these exact strings: 'C:\Windows\notepad.exe', 'C:\InvalidPath\file.txt', and 'C:\Windows\System32\calc.exe'.
PowerShell
Need a hint?

Use an array with @() and include the exact file paths as strings.

2
Set error action preference
Create a variable called errorAction and set it to the string 'Continue' to allow non-terminating errors to show but continue running.
PowerShell
Need a hint?

Assign the string 'Continue' to the variable $errorAction.

3
Try to get file info with non-terminating errors
Use a foreach loop with variable $file to go through $filePaths. Inside the loop, run Get-Item $file -ErrorAction $errorAction to get file info. This will show non-terminating errors for invalid paths.
PowerShell
Need a hint?

Use foreach to loop and Get-Item with the variable $file and -ErrorAction $errorAction.

4
Try to get file info with terminating errors and catch them
Set $errorAction to 'Stop'. Use a foreach loop with $file over $filePaths. Inside the loop, use try and catch blocks. In try, run Get-Item $file -ErrorAction $errorAction. In catch, print "Error caught: $($_.Exception.Message)".
PowerShell
Need a hint?

Use try-catch with Get-Item and -ErrorAction 'Stop'. In catch, print the error message with Write-Output.