2017-10-13 103 views
4

什麼是處理參數的好習慣,我什麼時候選擇什麼選項?正確使用參數

例如:平時我寫的功能是這樣的:

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

現在顯然這也是一個選項:

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

我可以,但是,沒有查出爲什麼要使用第二或真正的優勢是什麼使用這個。

回答

6

第二個Param()塊允許你做很多高級參數驗證。

,如果我需要寫最小輸入驗證短的功能,我會使用這樣的:

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

,但如果我需要寫的東西有先進的檢測是這樣的:

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 
} 

即使他們是類似的腳本,我絕對不會把它全部裝入頂部欄,第二個'做'更多。這實際上只是一個個案的基礎。

你可以看看this link的例子,你可以用擴展參數做什麼,但是如果你不需要這些隨意使用你喜歡的任何東西。

3

由於@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" 
} 

}

你也可以定義不同的參數設置,如果你的函數應支持不同的參數組合。此外,如果您是Parameter屬性的MandatoryPositional屬性,則還會通過Get-Help獲得「開箱即用」文檔。例如: -

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參數你會認爲這是可選參數的出括號。所以關於描述,驗證和文檔。

希望有所幫助。

+0

感謝您的信息。澄清了很多。將需要我的新腳本的第二塊。 – Jos