解釋 PowerShell 高階函式中的 Mandatory 屬性。
下面我們有一個 PowerShell 高階函式的示例,我們將嘗試瞭解強制引數是如何工作的。
function math_Operation{ [cmdletbinding()] param([int]$val1,[int]$val2) Write-Host "Multiply : $($val1*$val2)" Write-Host "Addition : $($val1+$val2)" Write-Host "Subtraction : $($val1-$val2)" Write-Host "Divide : $($val1+$val2)" }
當您執行上述示例並且沒有提供值時,指令碼不會提示您輸入值,預設情況下它將獲取值並執行程式。請參見下面的執行結果。
PS C:\WINDOWS\system32> math_Operation Multiply : 0 Addition : 0 Subtraction : 0 Divide : 0
即使您已聲明瞭兩個變數($val1, $val2),並且您沒有提供它們,該函式也不會提示您輸入值,而是獲取空值。若要使它們成為必需的,請使用 Mandatory **引數**,如下所示。
function math_Operation{ [cmdletbinding()] param([parameter(Mandatory=$True)] [int]$val1, [Parameter(Mandatory=$True)] [int]$val2) Write-Host "Multiply : $($val1*$val2)" Write-Host "Addition : $($val1+$val2)" Write-Host "Subtraction : $($val1-$val2)" Write-Host "Divide : $($val1+$val2)" }
輸出 −
PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation at command pipeline position 1 Supply values for the following parameters: val1: 20 val2: 10 Multiply : 200 Addition : 30 Subtraction : 10 Divide : 30
如您在輸出中看到的,當您指定 Mandatory 引數時,當您在未提供值的情況下執行指令碼時,它會提示您輸入這些變數的值。當您不提供變數的值時會發生什麼,強制引數是否接受該值?是的,它接受。它將空值作為整數變數的預設值。請參見下面的輸出。
PS C:\WINDOWS\system32> math_Operation cmdlet math_Operation at command pipeline position 1 Supply values for the following parameters: val1: val2: Multiply : 0 Addition : 0 Subtraction : 0 Divide : 0
請記住,上述預設值 0 被整數單變數接受,但如果您使用整數陣列 (int[]),則 PowerShell 不會接受空陣列,例如,
function print_number{ [cmdletbinding()] param( [parameter(Mandatory=$True)] [int[]]$numbers ) Write-Output "Integer Array" $numbers }
輸出 −
PS C:\WINDOWS\system32> print_number cmdlet print_number at command pipeline position 1 Supply values for the following parameters: numbers[0]: print_number : Cannot bind argument to parameter 'numbers' because it is an empty array. At line:1 char:1 + print_number + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_number], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAll o wed,print_number
但是,如果您為字串值和字串陣列提供空輸入,則它們都不會接受空字串或 null 字串。
示例
function print_String{ [cmdletbinding()] param( [parameter(Mandatory=$True)] [string]$name, [parameter(Mandatory=$True)] [string[]]$names ) $name $names }
輸出
PS C:\WINDOWS\system32> print_String cmdlet print_String at command pipeline position 1 Supply values for the following parameters: name: print_String : Cannot bind argument to parameter 'name' because it is an empty string. At line:1 char:1 + print_String + ~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [print_String], ParameterBindin g ValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl l owed,print_String
上述示例的結論是,當指定 Mandatory 引數時,null 或空值的接受取決於資料型別,並且任何集合都不會接受 null 值。
廣告