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!