📖 Scenario: You are writing a PowerShell script to process a list of files. Sometimes, files might not exist or have permission issues. Without error handling, the script stops when it hits a problem. You want to learn how to keep your script running even if some files cause errors.
🎯 Goal: Build a PowerShell script that tries to read content from a list of files. Use error handling to catch errors and continue processing all files without stopping the script.
📋 What You'll Learn
Create a list of file paths including some that do not exist
Add a variable to control error handling behavior
Use a try-catch block to handle errors when reading files
Print the content of files or an error message without stopping the script
💡 Why This Matters
🌍 Real World
Scripts often process many files or data sources. Errors like missing files or permission issues can stop scripts. Using error handling lets scripts continue working and handle problems gracefully.
💼 Career
Knowing how to handle errors is essential for automation, system administration, and scripting jobs. It helps create reliable scripts that don't fail unexpectedly.
Progress0 / 4 steps
1
Create a list of file paths
Create a variable called $filePaths and assign it an array with these exact strings: 'C:\temp\file1.txt', 'C:\temp\file2.txt', and 'C:\temp\nofile.txt'.
PowerShell
Hint
Use @( ... ) to create an array in PowerShell.
2
Add an error action preference variable
Create a variable called $ErrorActionPreference and set it to 'Stop' to make errors throw exceptions.
PowerShell
Hint
This setting makes PowerShell treat errors as terminating, so try-catch can catch them.
3
Use try-catch to read files safely
Write a foreach loop using $filePath to go through $filePaths. Inside the loop, use a try block to read the file content with Get-Content $filePath. Use a catch block to print "Error reading $filePath" if reading fails.
PowerShell
Hint
Use try { ... } catch { ... } to handle errors and keep the script running.
4
Print the results
Run the script so it prints the content of existing files or the error message for missing files. The output should show the content of C:\temp\file1.txt and C:\temp\file2.txt or error messages for C:\temp\nofile.txt.
PowerShell
Hint
If you see error messages for missing files but the script continues, your error handling works!
Practice
(1/5)
1. What is the main reason to use error handling in a PowerShell script?
easy
A. To change the script's output format
B. To make the script run faster
C. To add more comments to the script
D. To stop the script from crashing when an error happens
Solution
Step 1: Understand script failure
Without error handling, a script stops running when it hits an error.
Step 2: Role of error handling
Error handling catches errors so the script can continue running smoothly.
Final Answer:
To stop the script from crashing when an error happens -> Option D
A. The -ErrorAction SilentlyContinue prevents catch from running
B. The catch block is missing
C. Get-Item syntax is wrong
D. Write-Output cannot be used inside catch
Solution
Step 1: Understand -ErrorAction SilentlyContinue
This option stops errors from being thrown, so catch never triggers.
Step 2: Effect on error handling
Since no error is thrown, catch block is skipped, but script does not crash.
Final Answer:
The -ErrorAction SilentlyContinue prevents catch from running -> Option A
Quick Check:
-ErrorAction SilentlyContinue blocks catch = D [OK]
Hint: SilentlyContinue stops catch from catching errors [OK]
Common Mistakes:
Thinking catch block is missing
Assuming Get-Item syntax error
Believing Write-Output can't be in catch
5. You want your PowerShell script to try deleting a file, but if it fails, log the error and continue. Which script correctly uses error handling to do this?
hard
A. try { Remove-Item 'C:\file.txt' } catch { Write-Output 'Failed to delete file'; exit }
B. Remove-Item 'C:\file.txt' -ErrorAction Stop; Write-Output 'Continuing script'
C. try { Remove-Item 'C:\file.txt' } catch { Write-Output 'Failed to delete file' } Write-Output 'Continuing script'
D. Remove-Item 'C:\file.txt' -ErrorAction SilentlyContinue; Write-Output 'Failed to delete file'
Solution
Step 1: Check try-catch usage
try { Remove-Item 'C:\file.txt' } catch { Write-Output 'Failed to delete file' } Write-Output 'Continuing script' uses try to attempt deletion and catch to log failure without stopping.
Step 2: Confirm script continues
After catch, it outputs 'Continuing script', so script keeps running.
Final Answer:
try { Remove-Item 'C:\file.txt' } catch { Write-Output 'Failed to delete file' } Write-Output 'Continuing script' -> Option C
Quick Check:
Try-catch logs error and continues = C [OK]
Hint: Use try-catch and continue script after catch [OK]
Common Mistakes:
Using exit in catch stops script
Not using try-catch for error handling
Using SilentlyContinue but logging error anyway
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.