0
0
PowerShellscripting~15 mins

Throw statement in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Throw Statement in PowerShell
📖 Scenario: You are writing a PowerShell script to check if a user input number is positive. If the number is negative, you want to stop the script and show an error message.
🎯 Goal: Build a script that uses the throw statement to stop execution when a negative number is detected.
📋 What You'll Learn
Create a variable called number with a specific integer value.
Create a variable called threshold set to 0.
Use an if statement to check if number is less than threshold.
Use the throw statement to raise an error with the message 'Negative number detected!' if the condition is true.
Print 'Number is positive.' if no error is thrown.
💡 Why This Matters
🌍 Real World
Scripts often need to stop when something goes wrong. Using throw helps you catch problems early and show clear messages.
💼 Career
Knowing how to use throw is important for writing reliable scripts that handle errors properly in IT and automation jobs.
Progress0 / 4 steps
1
Create the number variable
Create a variable called number and set it to -5.
PowerShell
Need a hint?

Use $number = -5 to create the variable.

2
Create the threshold variable
Create a variable called threshold and set it to 0.
PowerShell
Need a hint?

Use $threshold = 0 to create the variable.

3
Add the if statement with throw
Write an if statement that checks if number is less than threshold. Inside the if, use throw with the message 'Negative number detected!'.
PowerShell
Need a hint?

Use if ($number -lt $threshold) { throw 'Negative number detected!' }.

4
Print the success message
Add a line to print 'Number is positive.' after the if statement.
PowerShell
Need a hint?

Use Write-Output 'Number is positive.' to print the message.