Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.5k views
in PowerShell by 6 7 9

How do I make a parameter required in PowerShell? I have tried to use Mandatory=$true but it's not worked for me and I got "Unexpected attribute parameter", can you guide me on how to set the parameter as mandatory in PowerShell?

param(
[string]$FirstName[Parameter(Mandatory=$true)],
[string]$Company[Parameter(Mandatory=$true)]
)

1 Answer

1 like 0 dislike
by 159 198 381
selected by
 
Best answer

To make a mandatory parameter in PowerShell, you should add the "Mandatory=$true" before the parameter definition, not after the parameter name as you did!

Mandatory Parameter in PowerShell

param(
     [Parameter(Mandatory=$true)]    
     [string]$FirstName,
     [Parameter(Mandatory=$true)]
     [string]$Company)

Optional Parameter in PowerShell

param(
     [string]$FirstName,
     [string]$Company )

For more details, Please check Use PowerShell to Make Mandatory Parameters

If you don’t ask, the answer is always NO!
...