0
0
PowerShellscripting~5 mins

Throw statement in PowerShell

Choose your learning style9 modes available
Introduction

The throw statement stops the script and shows an error message. It helps you catch problems early.

When you want to stop the script if something goes wrong.
When you need to show a clear error message to the user.
When a required file or input is missing.
When a condition is not met and you want to prevent further steps.
Syntax
PowerShell
throw "Error message here"

The throw keyword is followed by a string message in quotes.

It immediately stops the script and shows the message as an error.

Examples
This stops the script and shows the message "Something went wrong!".
PowerShell
throw "Something went wrong!"
This checks if a file exists. If not, it throws an error and stops.
PowerShell
if (-not (Test-Path "file.txt")) { throw "File not found!" }
This throws an error inside a try block and catches it to show a message.
PowerShell
try { throw "Manual error" } catch { Write-Host "Caught error: $_" }
Sample Program

This script defines a function that throws an error if the age is less than 18. The error is caught and shown.

PowerShell
function Check-Age {
    param([int]$age)
    if ($age -lt 18) {
        throw "Age must be 18 or older."
    } else {
        Write-Host "Age is valid: $age"
    }
}

try {
    Check-Age -age 16
} catch {
    Write-Host "Error caught: $_"
}
OutputSuccess
Important Notes

Use throw to stop the script when you find a serious problem.

You can catch thrown errors with try/catch blocks to handle them gracefully.

Throwing errors helps make your scripts more reliable and easier to debug.

Summary

throw stops the script and shows an error message.

Use it to catch problems early and prevent wrong results.

Combine with try/catch to handle errors nicely.