0
0
PowerShellscripting~10 mins

Why error handling prevents script failure in PowerShell - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch errors and prevent script failure.

PowerShell
try {
    Get-Item 'C:\nonexistentfile.txt'
} catch {
    Write-Host [1]
}
Drag options to blanks, or click blank then click option'
A'File not found, but script continues.'
BThrow
CExit
DStop-Process
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Exit' or 'Throw' inside catch which stops the script.
Not using quotes around the message string.
2fill in blank
medium

Complete the code to ignore errors and continue script execution.

PowerShell
Get-Content 'C:\missingfile.txt' -ErrorAction [1]
Drag options to blanks, or click blank then click option'
AInquire
BSilentlyContinue
CContinue
DStop
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Stop' which halts the script on error.
Using 'Continue' which still shows errors.
3fill in blank
hard

Fix the error in the code to handle exceptions properly.

PowerShell
try {
    Remove-Item 'C:\protectedfile.txt'
} catch [1] {
    Write-Host 'Cannot delete file.'
}
Drag options to blanks, or click blank then click option'
A-ErrorAction Stop
B-ErrorVariable err
CException
D[Exception]
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting square brackets around the exception type.
Using parameters like -ErrorAction inside catch parentheses.
4fill in blank
hard

Fill both blanks to create a try-catch block that logs errors and continues.

PowerShell
try {
    [1] 'C:\file.txt' -ErrorAction Stop
} catch [Exception] {
    [2] 'Error logged, continuing script.'
}
Drag options to blanks, or click blank then click option'
AGet-Content
BWrite-Host
CWrite-Output
DRemove-Item
Attempts:
3 left
💡 Hint
Common Mistakes
Using Remove-Item instead of Get-Content in try.
Using Write-Output instead of Write-Host in catch.
5fill in blank
hard

Fill all three blanks to handle errors and assign a default value.

PowerShell
$content = try {
    [1] 'C:\data.txt' -ErrorAction Stop
} catch {
    [2] = 'Default content'
    [3]
}
Drag options to blanks, or click blank then click option'
AGet-Content
B$content
DWrite-Host 'Using default content'; $content
Attempts:
3 left
💡 Hint
Common Mistakes
Not assigning the default value to the variable.
Not printing a message in catch.