The PowerShell function uses a required parameter instance _powershell

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.