- Courses
- đź’»Programming Languages
- 🪟PowerShell
- Scripting Fundamentals
- Functions and Modular Code
- Mandatory Parameters
On this page
PowerShell mandatory parameters
Updated on June 11, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Mandatory parameters are required inputs that must be supplied before a PowerShell function, script, or advanced function can run. They are implemented with the Mandatory argument of the [Parameter()] attribute and integrate with type conversion, validation attributes, pipeline binding, and parameter sets. Correct use of mandatory parameters prevents incomplete calls, improves error messages, and makes advanced functions safer and more predictable in both interactive and automated environments.
Concept and core behavior​
A mandatory parameter is a parameter marked as required during parameter binding. When a caller omits a mandatory parameter:
- PowerShell stops before executing the function body.
- Binding logic determines which parameters are missing.
- In interactive sessions, PowerShell prompts for each missing value.
The behavior is controlled by the Mandatory Boolean on [Parameter()], which defaults to $false and must be explicitly enabled.
function Show-Message {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Text
)
"Message: $Text"
}
Explanation: Mandatory = $true marks $Text as required. If Show-Message is called without -Text or a positional value, PowerShell does not run the function body and instead prompts for Text.
Declaring mandatory parameters​
Minimal declaration pattern​
function Show-Message {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Text
)
"Message: $Text"
}
Explanation: For Boolean arguments on [Parameter()], specifying the name alone (Mandatory) is equivalent to Mandatory = $true. [CmdletBinding()] turns the function into an advanced function, aligning its behavior with compiled cmdlets and enabling features such as -Verbose and -ErrorAction.
Multiple mandatory parameters​
function Add-Numbers {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[int]$A,
[Parameter(Mandatory)]
[int]$B
)
$A + $B
}
Explanation: Both $A and $B are required. If either is missing, PowerShell prompts for both. When both are supplied, the function executes normally and returns the sum.
Prompting behavior and HelpMessage​
When mandatory parameters are missing, PowerShell displays a standard prompt:
cmdlet Show-Message at command pipeline position 1
Supply values for the following parameters:
Text:
The user must enter a value for each missing parameter before execution continues. This behavior is driven by the parameter binding engine and applies to functions, scripts, and compiled cmdlets that declare mandatory parameters.
The HelpMessage argument on [Parameter()] customizes the prompt text:
function Get-ServerStatus {
[CmdletBinding()]
param(
[Parameter(Mandatory, HelpMessage = "Enter the target server name.")]
[string]$ComputerName
)
"Checking status for $ComputerName"
}
Explanation: When Get-ServerStatus is called without -ComputerName, the prompt includes the custom help message, guiding the user toward the proper parameter values. HelpMessage is intended for short, inline guidance; longer descriptions belong in comment‑based help.
In non‑interactive contexts (CI pipelines, scheduled tasks, background jobs, non‑interactive remoting), prompting is undesirable because it causes the command to hang waiting for input that never arrives. In those scenarios, all mandatory parameters must be supplied explicitly, or the design should avoid mandatory parameters altogether.
Named, positional, and splatted calls​
Mandatory parameters participate in the normal binding order: named parameters first, then positional parameters, then pipeline binding. The parameter is considered satisfied as soon as it is successfully bound, regardless of how the value is supplied.
Add-Numbers -A 5 -B 7 # named
Add-Numbers 5 7 # positional
$params = @{
A = 5
B = 7
}
Add-Numbers @params # splatting
Explanation: Named arguments bind by parameter name. Positional arguments bind by declared position (or explicit Position in [Parameter()]). Splatting expands a hashtable into named parameters. If a mandatory parameter is not bound by any of these mechanisms, PowerShell treats it as missing and prompts (in interactive sessions).
Type conversion and mandatory parameters​
Mandatory parameters fully participate in PowerShell’s type conversion rules. Binding occurs only after successful conversion to the declared type.
function Multiply {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[int]$X,
[Parameter(Mandatory)]
[int]$Y
)
$X * $Y
}
Multiply -X "3" -Y "4"
Explanation: "3" and "4" are strings. PowerShell converts them to int during binding. If conversion fails (for example, "hello"), a ParameterBindingException is thrown before the function body runs. Advanced functions use culture‑invariant conversion; compiled cmdlets use culture‑sensitive conversion, which can matter for dates and numbers in localized formats.
Validation attributes on mandatory parameters​
Validation attributes run as part of parameter binding, before any function logic executes. They combine naturally with Mandatory to enforce both presence and correctness of parameter values.
ValidateRange​
function Set-Age {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateRange(1, 120)]
[int]$Age
)
"Age set to $Age"
}
Explanation: If $Age is omitted, PowerShell prompts. If the user enters a value outside 1–120, [ValidateRange()] fails and PowerShell reports a validation error, preventing the function from running with invalid data.
ValidatePattern​
function Set-ServerName {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidatePattern("^[a-zA-Z][a-zA-Z0-9\-]{1,14}$")]
[string]$Name
)
"Server name accepted: $Name"
}
Explanation: The regular expression enforces a naming convention: a letter followed by 1–14 letters, digits, or hyphens. The parameter is both mandatory and constrained to valid patterns.
ValidateScript​
function Import-DataFile {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateScript({
if (-not (Test-Path $_)) {
throw "File not found: $_"
}
$true
})]
[string]$FilePath
)
"Importing: $FilePath"
}
Explanation: [ValidateScript()] runs a script block that can perform arbitrary checks. Throwing inside the block produces clear error messages when validation fails. The parameter is mandatory and must also pass the script‑based validation.
ValidateNotNull, ValidateNotNullOrEmpty, ValidateNotNullOrWhiteSpace​
function Write-Entry {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Message
)
Write-Output $Message
}
Explanation: The parameter is mandatory and must not be $null or an empty string. In newer PowerShell versions, [ValidateNotNullOrWhiteSpace()] can be used to also reject whitespace‑only strings, which is often the safest choice for identifiers and names.
Mandatory parameters and pipeline input​
Mandatory parameters can accept pipeline input via ValueFromPipeline or ValueFromPipelineByPropertyName. When pipeline binding succeeds, prompting is not needed because the mandatory parameter is already satisfied.
ValueFromPipeline​
function Show-Item {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
$Item
)
process {
"Item: $Item"
}
}
"apple", "banana" | Show-Item
Explanation: Each pipeline value binds to $Item. Because the pipeline supplies the mandatory parameter, no prompt occurs. The process block runs once per input object; without process, only the last item would be processed.
ValueFromPipelineByPropertyName​
function Restart-NamedService {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[string]$Name
)
process {
"Restarting service: $Name"
}
}
Get-Service "bits", "wuauserv" | Restart-NamedService
Explanation: Get-Service outputs objects with a Name property. ValueFromPipelineByPropertyName binds that property to the mandatory $Name parameter. Again, no prompt occurs because the pipeline provides the value. If neither the command line nor the pipeline supplies a value for a mandatory parameter, PowerShell prompts.
Mandatory parameters in parameter sets​
Parameter sets use mandatory parameters to define mutually exclusive calling patterns and to make required combinations explicit.
function Connect-Service {
[CmdletBinding(DefaultParameterSetName = "ByName")]
param(
[Parameter(Mandatory, ParameterSetName = "ByName")]
[string]$ServiceName,
[Parameter(Mandatory, ParameterSetName = "ById")]
[int]$ServiceId,
[Parameter(ParameterSetName = "ByName")]
[Parameter(ParameterSetName = "ById")]
[int]$TimeoutSeconds = 30
)
switch ($PSCmdlet.ParameterSetName) {
"ByName" { "Connecting to service '$ServiceName' with timeout $TimeoutSeconds s" }
"ById" { "Connecting to service ID $ServiceId with timeout $TimeoutSeconds s" }
}
}
Explanation:
ServiceNameis mandatory in theByNameset.ServiceIdis mandatory in theByIdset.TimeoutSecondsis optional and shared across both sets.DefaultParameterSetNamedefines the default when only common parameters are supplied.
Supplying parameters from different sets in one call (for example, -ServiceName and -ServiceId together) causes a ParameterBindingException because PowerShell cannot determine which set to use. This is a deliberate safeguard that prevents ambiguous calls.
Mandatory parameters, default values, and design considerations​
A parameter with a default value is not logically mandatory, even if Mandatory = $true is specified. The default value means the function can run without explicit input, which contradicts the idea of a required parameter.
param(
[Parameter(Mandatory)]
[string]$Name = "DefaultName"
)
Explanation: This pattern is technically allowed but conceptually confusing. The parameter is marked mandatory yet has a default. For clarity and maintainability:
- Use mandatory parameters when explicit input is required every time.
- Use defaults for optional parameters that can safely fall back to a known value.
- Avoid combining
Mandatorywith a default unless there is a very specific, well‑documented reason (for example, enforcing prompting in some hosts while still exposing a default for programmatic callers).
In many designs, a non‑mandatory parameter with a well‑chosen default and strong validation attributes provides a better user experience than a mandatory parameter with a default.
Mandatory parameters in CI, automation, and non‑interactive runs​
In continuous integration pipelines, scheduled tasks, and other non‑interactive environments, prompting for mandatory parameters is a common source of hangs. Typical patterns to avoid this:
- Always supply all mandatory parameters explicitly in scripts and pipeline definitions.
- Use parameter sets to make required combinations explicit and avoid ambiguous calls.
- For automation‑only functions, consider using optional parameters with validation and clear defaults instead of mandatory parameters.
- When interactive and non‑interactive use must coexist, separate entry points (for example, an interactive wrapper and a non‑interactive core function) often produce clearer behavior than trying to make one function serve both roles.
Some teams also enforce -NonInteractive or similar patterns at the host or pipeline level to ensure that any unexpected prompt fails fast rather than hanging indefinitely.
Summary of benefits and best practices​
Well‑designed mandatory parameters:
- Enforce required input and prevent incomplete calls.
- Trigger validation and type conversion before any logic runs.
- Integrate cleanly with pipeline input and parameter sets.
- Improve error messages and user guidance via
HelpMessage. - Make advanced functions more robust and predictable in both interactive and automated scenarios.
Recommended practices:
- Use
[Parameter(Mandatory)]only for truly required parameters. - Combine with validation attributes (
ValidateRange,ValidatePattern,ValidateScript,ValidateNotNullOrEmpty,ValidateNotNullOrWhiteSpace) to enforce correct parameter values. - Use parameter sets to model different required input combinations.
- Avoid mandatory parameters in non‑interactive automation unless all values are always supplied.
- Prefer clear, explicit design over clever combinations of
Mandatoryand default values.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Parameter Binding
Next
Pipeline Input
-
Concept and core behavior
-
Declaring mandatory parameters
- Minimal declaration pattern
- Multiple mandatory parameters
-
Prompting behavior and HelpMessage
-
Named, positional, and splatted calls
-
Type conversion and mandatory parameters
-
Validation attributes on mandatory parameters
- ValidateRange
- ValidatePattern
- ValidateScript
- ValidateNotNull, ValidateNotNullOrEmpty, ValidateNotNullOrWhiteSpace
-
Mandatory parameters and pipeline input
- ValueFromPipeline
- ValueFromPipelineByPropertyName
-
Mandatory parameters in parameter sets
-
Mandatory parameters, default values, and design considerations
-
Mandatory parameters in CI, automation, and non‑interactive runs
-
Summary of benefits and best practices
