PowerShell函數(shù)中限制數(shù)組參數(shù)個數(shù)的例子
本文介紹PowerShell自定義函數(shù)時,可以使用數(shù)組來傳遞多個參數(shù)。數(shù)組傳遞參數(shù)時,參數(shù)個數(shù)本身無法限制,PowerShell函數(shù)提供了一個方法來限制數(shù)組中參數(shù)的個數(shù)。
PowerShell函數(shù)可以接受數(shù)組作為輸入?yún)?shù)。而且不需要將數(shù)組定義好后再傳給PowerShell函數(shù),而可以直接將一個逗號分隔的字符串?dāng)?shù)組當(dāng)作參數(shù)來傳遞,如:Add-User -UserName 'splaybow1','splaybow2','splaybow3'。這個函數(shù)的定義如下:
function Add-User
{
param
(
[String[]]
$UserName
)
$UserName | ForEach-Object { “Adding $_” }
}
函數(shù)調(diào)用時如下:
Adding Tobias
PS> Add-User -UserName 'Tobias', 'Nina', 'Cofi'
Adding Tobias
Adding Nina
Adding Cofi
數(shù)組元素后面可以再跟上千兒八百個,但這樣不安全,我們得要參數(shù)PowerShell函數(shù)定義時來做出一些限制。
function Add-User
{
param
(
[ValidateCount(1,3)]
[String[]]
$UserName
)
$UserName | ForEach-Object { “Adding $_” }
}
注意函數(shù)中使用了“[ValidateCount(1,3)]”這句,這表示可以接受的參數(shù)個數(shù)是1-3之間,即1個、2個、3個都可以。但不能超了,也不能少了。
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.
上面第二個測試用例就提示:函數(shù)最大可接受的參數(shù)個數(shù)為3,而我們實際傳了4個,所以失敗了。
關(guān)于PowerShell函數(shù)限制數(shù)組參數(shù)個數(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)的定義、用法以及示例,非常簡單實用,有需要的朋友可以參考下2014-10-10PowerShell數(shù)組結(jié)合switch語句產(chǎn)生的奇特效果介紹
這篇文章主要介紹了PowerShell數(shù)組結(jié)合switch語句產(chǎn)生的奇特效果介紹,產(chǎn)生了類似枚舉的效果,需要的朋友可以參考下2014-08-08PowerShell遠程安裝MSI安裝包、EXE可執(zhí)行程序的方法
這篇文章主要介紹了PowerShell遠程安裝MSI安裝包、EXE可執(zhí)行程序的方法,需要的朋友可以參考下2014-05-05PowerShell實現(xiàn)查詢打開某個文件的默認應(yīng)用程序
這篇文章主要介紹了PowerShell實現(xiàn)查詢打開某個文件的默認應(yīng)用程序,本文通過C#調(diào)用Windows API來實現(xiàn)這個需求,需要的朋友可以參考下2015-06-06PowerShell 讀取性能計數(shù)器二進制文件(.blg)記錄并匯總計算
由于監(jiān)控及報告需要,要統(tǒng)計性能計數(shù)器每天數(shù)值情況,確認數(shù)據(jù)庫服務(wù)器的運行狀況。若打開計數(shù)器填寫,比較麻煩,現(xiàn)在統(tǒng)計用 powershell 來讀取計數(shù)器的值2016-11-11