Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of parameters

What is a good practice to handle parameters, when do I choose what option?

Example: usually I write functions like this:

function Do-Something ($variable1, $variable2, $variable3....) 
    { Do Stuff }

Now apparently this is also an option:

Param(
    [Parameter(Position=0,
        Mandatory=$True,
        ValueFromPipeline=$True)]
    [string]$userName,
    ...
)

I can, however, not find out why to use the second, or what the advantages really are to use this.

like image 826
Jos Avatar asked Jan 03 '23 08:01

Jos


1 Answers

the second Param() block allows you to do a lot of advanced param validation.

if I need to write a short function with minimal input validation i'll use something like this:

Function Test-Port ([string]$Server,[uint16]$Port=80,[uint16]$Timeout = 3000) {
    #code here
}

but if I need to write something with advanced checking like this:

function Get-SiteCert{
    [CmdletBinding(DefaultParameterSetName = "Return")]
    Param(
        [Parameter(Mandatory=$true,Position=0)]
        [string]$Server,
        [Parameter(Position=1)]
        [uint16]$Port=443,
        [Parameter(Mandatory=$false, ParameterSetName="RawObj")]
        [switch]$Raw,
        [Parameter(Mandatory=$false, ParameterSetName="Export")]
        [switch]$Export,
        [Parameter(Mandatory=$true, ParameterSetName="Export")]
        [string]$Path,
        [uint16]$Timeout=3000
    )
    #code here
}

I'm definitely not fitting it all into the top bar, even though they're similar scripts, the second one 'does' a lot more. it's really just a case by case basis.

you can check out this link for examples of what you can do with the expansive parameters, but if you don't need these feel free to keep using whichever you prefer.

like image 51
colsw Avatar answered Jan 14 '23 03:01

colsw