PowerShell函數(shù)中限制數(shù)組參數(shù)個(gè)數(shù)的例子
本文介紹PowerShell自定義函數(shù)時(shí),可以使用數(shù)組來傳遞多個(gè)參數(shù)。數(shù)組傳遞參數(shù)時(shí),參數(shù)個(gè)數(shù)本身無法限制,PowerShell函數(shù)提供了一個(gè)方法來限制數(shù)組中參數(shù)的個(gè)數(shù)。
PowerShell函數(shù)可以接受數(shù)組作為輸入?yún)?shù)。而且不需要將數(shù)組定義好后再傳給PowerShell函數(shù),而可以直接將一個(gè)逗號分隔的字符串?dāng)?shù)組當(dāng)作參數(shù)來傳遞,如:Add-User -UserName 'splaybow1','splaybow2','splaybow3'。這個(gè)函數(shù)的定義如下:
function Add-User
{
param
(
[String[]]
$UserName
)
$UserName | ForEach-Object { “Adding $_” }
}
函數(shù)調(diào)用時(shí)如下:
Adding Tobias
PS> Add-User -UserName 'Tobias', 'Nina', 'Cofi'
Adding Tobias
Adding Nina
Adding Cofi
數(shù)組元素后面可以再跟上千兒八百個(gè),但這樣不安全,我們得要參數(shù)PowerShell函數(shù)定義時(shí)來做出一些限制。
function Add-User
{
param
(
[ValidateCount(1,3)]
[String[]]
$UserName
)
$UserName | ForEach-Object { “Adding $_” }
}
注意函數(shù)中使用了“[ValidateCount(1,3)]”這句,這表示可以接受的參數(shù)個(gè)數(shù)是1-3之間,即1個(gè)、2個(gè)、3個(gè)都可以。但不能超了,也不能少了。
PS> Add-User -UserName 'Tobias', 'Nina'
Adding Tobias
Adding Nina
PS> Add-User -UserName 'Tobias', 'Nina', 'Cofi', 'splaybow'
Add-User : Cannot validate argument on parameter 'UserName'. The number of provided
arguments, (4), exceeds the maximum number of allowed arguments (3). Provide fewer than 3
arguments, and then try the command again.
上面第二個(gè)測試用例就提示:函數(shù)最大可接受的參數(shù)個(gè)數(shù)為3,而我們實(shí)際傳了4個(gè),所以失敗了。
關(guān)于PowerShell函數(shù)限制數(shù)組參數(shù)個(gè)數(shù),本文就介紹這么多,希望對您有所幫助,謝謝!
相關(guān)文章
Powershell創(chuàng)建數(shù)組正確、更快的方法
這篇文章主要介紹了Powershell創(chuàng)建數(shù)組正確、更快的方法,Powershell使用ArrayList創(chuàng)建數(shù)組的例子,需要的朋友可以參考下2014-07-07Windows Powershell For 循環(huán)
這篇文章主要介紹了Windows Powershell For 循環(huán)的定義、用法以及示例,非常簡單實(shí)用,有需要的朋友可以參考下2014-10-10PowerShell數(shù)組結(jié)合switch語句產(chǎn)生的奇特效果介紹
這篇文章主要介紹了PowerShell數(shù)組結(jié)合switch語句產(chǎn)生的奇特效果介紹,產(chǎn)生了類似枚舉的效果,需要的朋友可以參考下2014-08-08PowerShell遠(yuǎn)程安裝MSI安裝包、EXE可執(zhí)行程序的方法
這篇文章主要介紹了PowerShell遠(yuǎn)程安裝MSI安裝包、EXE可執(zhí)行程序的方法,需要的朋友可以參考下2014-05-05Powershell小技巧之非相同域或信任域也能遠(yuǎn)程
這篇文章主要介紹了使用Powershell在非相同域或信任域也能遠(yuǎn)程的方法以及如何設(shè)置powershell遠(yuǎn)程處理的方法,需要的朋友可以參考下2014-10-10Windows Powershell條件表達(dá)式之條件操作符
條件表達(dá)式返回的結(jié)果是$true和$false,在條件表達(dá)式中可以包含屬性引用和方法調(diào)用2014-10-10PowerShell實(shí)現(xiàn)查詢打開某個(gè)文件的默認(rèn)應(yīng)用程序
這篇文章主要介紹了PowerShell實(shí)現(xiàn)查詢打開某個(gè)文件的默認(rèn)應(yīng)用程序,本文通過C#調(diào)用Windows API來實(shí)現(xiàn)這個(gè)需求,需要的朋友可以參考下2015-06-06PowerShell 讀取性能計(jì)數(shù)器二進(jìn)制文件(.blg)記錄并匯總計(jì)算
由于監(jiān)控及報(bào)告需要,要統(tǒng)計(jì)性能計(jì)數(shù)器每天數(shù)值情況,確認(rèn)數(shù)據(jù)庫服務(wù)器的運(yùn)行狀況。若打開計(jì)數(shù)器填寫,比較麻煩,現(xiàn)在統(tǒng)計(jì)用 powershell 來讀取計(jì)數(shù)器的值2016-11-11