PowerShell function parameter specifies a data type instance _powershell

Source: Internet
Author: User

This article describes the benefits of setting a strong type for a required parameter when you create a custom function in PowerShell, and how to set it.

To improve the security of the required parameters, the best practice defined by the PowerShell function tells us to set the strong type for the required arguments. This is why, let's look at an example.

Copy Code code as follows:

function Test-me {
Param
(
[Parameter (mandatory= $true, helpmessage= ' Enter number of euros! ')]
$Euro
)
$Dollar = $Euro * 1.4
$Dollar
}

The above example is the receiving user entering a euro value, and then outputting the dollar value. The equivalent of a conversion between two currencies. The effect of actual execution is surprising, and see:
Copy Code code as follows:

ps> Test-me-euro 100
140
Ps> Test-me
Cmdlet test-me at command pipeline position 1
Supply values for the following parameters:
(Type!?? for help.)
euro:100
100

Tested here two times, the first test is not a problem: 100*1.4=140. But the second Test on the egg pain, how 100*1.4 still equal to 100? In fact, the input of 100 is treated as a string, not a number. So a string multiplied by 1.4, which is equivalent to repeating the string 1.4 times, rounding, that is repeating 1 times, that's the same as it is, so you know how this 100 came from?

Well, that's what we call security. Do not set strong type unsafe for required parameters! Let's set it to the double type.

Copy Code code as follows:

function Test-me {
Param
(
[Parameter (mandatory= $true, helpmessage= ' Enter number of euros! ')]
[Double]
$Euro
)
$Dollar = $Euro * 1.4
$Dollar
}

You can try this piece of code will not appear before the problem. Because it adds a [double] directive, it acts as a mandatory data type.

About the required parameters for the PowerShell function to set the strong type, 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.