This article describes how to add required parameters when PowerShell creates a custom function, and you can use mandatory keywords.
By default, parameters are optional (optional) in PowerShell custom functions. If you want to set a parameter to a required parameter, you must set a mandatory declaration on it.
Copy Code code as follows:
function test-function
{
Param
[Parameter (mandatory= $true)]
$p 1,
$p 2= ' P2 '
)
Write-host "p1= $p 1, p2= $p 2"
}
In the example function above, parameter $P1 is a required parameter because the mandatory= $true is set, and $P2 does not make any settings, the default is optional. In accordance with the best practices defined by the PowerShell function, the optional parameters have to be set to a default value, to be remembered.
When we call this function, if we run the test-function directly without entering the parameter, we are prompted to enter the P1.
Copy Code code as follows:
Ps> test-function
Cmdlet test-me at command pipeline position 1
Supply values for the following parameters:
P1:
By the way, in PowerShell 3.0, [Parameter (mandatory= $true)] This sentence can be written in [Parameter (mandatory)], which means that the part "= $true" can be omitted. Write less is certainly less good, but if you write less, put the environment before the PowerShell 3.0-such as PowerShell 2.0, it will not run. It seems that the fish and bear's paw can not be both, we have to know how to choose Ah!
About the PowerShell function set required parameters, this article on the introduction of so many, I hope to help you, thank you!