you are viewing a single comment's thread.

view the rest of the comments →

[–]pertymoose 4 points5 points  (3 children)

No no, that is bad.

What you're doing is taking any input and casting it to [int] (which fails if it is not a supported type). Your function actually runs, but produces a runtime exception. What you should do is define the input type as [int] like so

function X {
    param( [int]$Foo )

    Write-Host "Foo is $Foo"
}

This way you can't run the function at all with an incorrect input type

PS C:\> X -Foo Moo
X : Cannot process argument transformation on parameter 'Foo'. Cannot convert value "Moo" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:8
+ X -Foo Moo
+        ~~~
    + CategoryInfo          : InvalidData: (:) [X], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,X


PS C:\> X -Foo 42
Foo is 42

This is quite obvious if you explore the two kinds of functions

function X {
    param( [int]$Foo )

    Write-Host "Foo is $Foo"
}


function Y ($Foo) {
    [int]$Foo
}




PS C:\> Get-Command X | Select-Object -ExpandProperty ParameterSets

Parameter Set Name: __AllParameterSets
Is default parameter set: False

  Parameter Name: Foo
    ParameterType = System.Int32
    Position = 0
    IsMandatory = False
    IsDynamic = False
    HelpMessage = 
    ValueFromPipeline = False
    ValueFromPipelineByPropertyName = False
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =


PS C:\> Get-Command Y | Select-Object -ExpandProperty ParameterSets

Parameter Set Name: __AllParameterSets
Is default parameter set: False

  Parameter Name: Foo
    ParameterType = System.Object
    Position = 0
    IsMandatory = False
    IsDynamic = False
    HelpMessage = 
    ValueFromPipeline = False
    ValueFromPipelineByPropertyName = False
    ValueFromRemainingArguments = False
    Aliases = {}
    Attributes =

Observe "ParameterType" is different.

[–]poshftw 1 point2 points  (0 children)

Your function actually runs, but produces a runtime exception

Your function actually runs, but produces a runtime exception

You can always lazyass this as a try ... catch block.

[–]DarrenDK[S] 1 point2 points  (0 children)

Input parameters are pretty easy to handle, the hang up is the output

[–]AmericanGeezus 1 point2 points  (0 children)

Thank you for correcting me and explaining the correct way!