Proper use of parameters

What is good practice for handling parameters when I can choose which option?

Example: usually I write such functions:

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 may, however, not find out why to use the second, or what advantages should really use it.

+4
source share
2 answers

the second block Param()allows a lot of advanced parameter checking.

if I need to write a short function with minimal input verification, I will 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 extended validation as follows:

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
}

, , - "". .

, , , .

+6

@ConnorLSW , . Param Validate, :

Function Foo
{
Param(
    [Parameter(Mandatory=$true,Position=0)]
    [ValidateSet("Tom","Dick","Jane")]
    [String]
    $Name
,
    [ValidateRange(21,65)]
    [Int]
    $Age
,
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    [string]
    $Path
)
Process
{
    write-host "New-Foo"
}

}

, . , " " Get-Help, Mandatory Positional Parameter. :.

 get-help Foo -Detailed

 NAME
   Foo

 SYNTAX
Foo [-Name] {Tom | Dick | Jane} [[-Age] <int>] [-Path <string>]  [<CommonParameters>]


PARAMETERS
-Age <int>

-Name <string>

-Path <string>

<CommonParameters>
    This cmdlet supports the common parameters: Verbose, Debug,
    ErrorAction, ErrorVariable, WarningAction, WarningVariable,
    OutBuffer, PipelineVariable, and OutVariable. For more information, see 
    about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). 


ALIASES
   None

REMARKS
   None

Age , . , .

, .

+3

Source: https://habr.com/ru/post/1687424/


All Articles