本文介紹PowerShell自定義函數(shù)中使用參數(shù)集時(shí),怎么設(shè)置系統(tǒng)自動(dòng)識(shí)別參數(shù)的數(shù)據(jù)類型。
識(shí)別參數(shù)類型的一個(gè)好處就是,在使用參數(shù)集時(shí),不需要每次都指定參數(shù)名稱了。
請(qǐng)看下面這個(gè)Test-Binding函數(shù)。這個(gè)PowerShell函數(shù)在設(shè)置參數(shù)集的時(shí)候,為參數(shù)集中的第一個(gè)參數(shù)設(shè)置了數(shù)據(jù)類型,這樣在調(diào)用函數(shù)時(shí),就可以自動(dòng)判斷一個(gè)參數(shù)值它應(yīng)該賦給哪個(gè)參數(shù)了。
復(fù)制代碼 代碼如下:
function Test-Binding {
[CmdletBinding(DefaultParameterSetName='Name')]
param(
[Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
[Int]
$id,
[Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
[String]
$name
)
$set = $PSCmdlet.ParameterSetName
“You selected $set parameter set”
if ($set -eq ‘ID') {
“The numeric ID is $id”
} else {
“You entered $name as a name”
}
}
注意函數(shù)中參數(shù)$id上面的[int]和參數(shù)$name上面的[String]。有這了這樣的函數(shù)定義,那我們?cè)谡{(diào)用時(shí)就方便了,如果傳一個(gè)字符串給它,它會(huì)把這個(gè)參數(shù)當(dāng)作是$name,而傳一個(gè)數(shù)字給它,這個(gè)參數(shù)會(huì)被當(dāng)作是$id。且看如下調(diào)用函數(shù)的示例。
復(fù)制代碼 代碼如下:
PS> Test-Binding -Name hallo
You selected Name parameter set
You entered hallo as a name
PS> Test-Binding -Id 12
You selected ID parameter set
The numeric ID is 12
PS> Test-Binding hallo
You selected Name parameter set
You entered hallo as a name
PS> Test-Binding 12
You selected ID parameter set
The numeric ID is 12
上面一共做了4次調(diào)用,前兩次調(diào)用都指定了參數(shù)名,沒有什么好說的。后面兩次都沒有指定參數(shù)名稱,但執(zhí)行的結(jié)果跟前兩次一模一樣,這表示PowerShell函數(shù)自動(dòng)識(shí)別了輸入?yún)?shù)要調(diào)用的哪個(gè)參數(shù)名稱。
關(guān)于PowerShell函數(shù)參數(shù)集自動(dòng)識(shí)別參數(shù)數(shù)據(jù)類型,本文就介紹這么多,希望對(duì)您有所幫助,謝謝!
您可能感興趣的文章:- PowerShell腳本實(shí)現(xiàn)網(wǎng)卡DHCP自動(dòng)獲取IP地址、設(shè)置靜態(tài)IP地址的方法
- PowerShell小技巧實(shí)現(xiàn)IE Web自動(dòng)化
- PowerShell腳本開發(fā)之嘗試登錄ftp
- PowerShell 自動(dòng)備份oracle并上傳到ftp