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