0
0
PowerShellscripting~15 mins

Parameter attributes (Mandatory, ValidateSet) in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Parameter Attributes: Mandatory and ValidateSet in PowerShell
📖 Scenario: You are creating a PowerShell script to manage user roles in a small company. The script will accept a username and a role to assign. To avoid errors, you want to make sure the username is always provided and the role is one of the allowed options.
🎯 Goal: Build a PowerShell script that uses parameter attributes Mandatory and ValidateSet to ensure the user inputs a username and selects a valid role from a predefined list.
📋 What You'll Learn
Create a function called Set-UserRole with parameters Username and Role.
Make the Username parameter mandatory.
Restrict the Role parameter to only accept Admin, User, or Guest using ValidateSet.
Print a confirmation message showing the username and assigned role.
💡 Why This Matters
🌍 Real World
Scripts often need to ensure users provide required information and select valid options to avoid mistakes.
💼 Career
Knowing how to enforce parameter rules helps create reliable and user-friendly automation scripts in IT and DevOps roles.
Progress0 / 4 steps
1
Create the function with parameters
Write a PowerShell function named Set-UserRole with two parameters: Username and Role. Do not add any attributes yet.
PowerShell
Need a hint?

Define the function and list the parameters inside param().

2
Make the Username parameter mandatory
Add the [Parameter(Mandatory=$true)] attribute to the Username parameter inside the param() block.
PowerShell
Need a hint?

Use [Parameter(Mandatory=$true)] just before $Username.

3
Restrict Role parameter with ValidateSet
Add the [ValidateSet('Admin','User','Guest')] attribute to the Role parameter inside the param() block.
PowerShell
Need a hint?

Use [ValidateSet('Admin','User','Guest')] just before $Role.

4
Print confirmation message
Inside the function body, add a Write-Host statement that prints: "User <Username> assigned role <Role>" using the parameters.
PowerShell
Need a hint?

Use Write-Host "User $Username assigned role $Role" inside the function.