SoFunction
Updated on 2025-03-10

PowerShell function parameter specifies data type instance

This article introduces what are the benefits of setting strong types for required parameters when creating custom functions in PowerShell and how to set them.

In order to improve the security of required parameters, the best practices for PowerShell function definitions tell us that we should set strong types for required parameters. Why is this? Let’s take an example.

Copy the codeThe code is as follows:

function Test-Me {
    param
    (
        [Parameter(Mandatory=$true, HelpMessage='Enter number of EUROs!')]
        $Euro
    )
    $Dollar = $Euro * 1.4
    $Dollar
}

The above example is to receive a user input an Euro value and then output a US dollar value. It is equivalent to making some conversions between two currencies. The actual execution effect is surprising, let's see:
Copy the codeThe code is 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

I tested it here twice, and the first test has no problem: 100*1.4=140. But the second test was so painful. Why is 100*1.4 equal to 100? Actually, this is the case, the input 100 is treated as a string, not a number. So multiplying a string by 1.4 is equivalent to repeating the string 1.4 times and rounding it, that is repeated 1 time, and that is still the same, so do you know how this 100 comes from?

OK, that's what we call security. It is not safe to not set strong types for required parameters! Let's set it to Double type.

Copy the codeThe code is as follows:

function Test-Me {
    param
    (
        [Parameter(Mandatory=$true, HelpMessage='Enter number of EUROs!')]
        [Double]
        $Euro
    )
    $Dollar = $Euro * 1.4
    $Dollar
}

You can try whether this code will have any previous problems. Because a [double] instruction is added here, it plays a role in forcing data types.

This article introduces so much about setting strong types for the required parameters of PowerShell function. I hope it will be helpful to you. Thank you!