0
0
PowerShellscripting~10 mins

Custom error messages in PowerShell - Interactive Code Practice

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

Complete the code to display a custom error message when a file is not found.

PowerShell
try {
    Get-Content -Path 'nonexistent.txt'
} catch {
    Write-Host [1]
}
Drag options to blanks, or click blank then click option'
AError occurred
BFile not found!
C"File not found! Please check the path."
D"An error happened"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the message
Using a variable name instead of a string
2fill in blank
medium

Complete the code to throw a custom error with the message 'Invalid input detected'.

PowerShell
if ($input -eq $null) {
    [1] 'Invalid input detected'
}
Drag options to blanks, or click blank then click option'
AWrite-Error
BThrow
CWrite-Host
DExit
Attempts:
3 left
💡 Hint
Common Mistakes
Using Write-Error instead of Throw for terminating errors
Using Write-Host which only prints text
3fill in blank
hard

Fix the error in the code to correctly catch and display a custom error message.

PowerShell
try {
    Remove-Item -Path 'C:\temp\file.txt'
} catch {
    Write-Host [1]
}
Drag options to blanks, or click blank then click option'
A$_.Exception.Message
B$_.Message
C$error.Message
D$error[0].Message
Attempts:
3 left
💡 Hint
Common Mistakes
Using $error which is a global array, not the current error
Using $_.Message which does not exist
4fill in blank
hard

Fill both blanks to create a function that throws a custom error with a given message.

PowerShell
function Throw-CustomError {
    param([string]$msg)
    [1] [2]
}
Drag options to blanks, or click blank then click option'
AThrow
B"$msg"
C$msg
DWrite-Error
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around $msg which makes it a literal string '$msg'
Using Write-Error instead of Throw for terminating errors
5fill in blank
hard

Fill all three blanks to catch an error and throw a new custom error with a modified message.

PowerShell
try {
    Get-Item -Path 'C:\invalid\file.txt'
} catch {
    $msg = $_.[1]
    $newMsg = "Custom error: $msg"
    [2] [3]
}
Drag options to blanks, or click blank then click option'
AException.Message
BThrow
C$newMsg
DMessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using $_.Message instead of $_.Exception.Message for detailed error
Using Write-Error instead of Throw for terminating errors
Passing the variable name as a string instead of the variable value