PowerShell函數(shù)實(shí)現(xiàn)類(lèi)似重載功能實(shí)例
本文介紹PowerShell自定義函數(shù)是否支持重載,如果支持,如何重載?如果不支持,如何實(shí)現(xiàn)與重載相似的效果?
鄭重聲明:PowerShell自定義函數(shù)不支持重載!也就是說(shuō),你不能定義兩個(gè)同名的PowerShell函數(shù),不管參數(shù)個(gè)數(shù)、順序、類(lèi)型是否相同。既然PowerShell自定義函數(shù)不支持重載功能,那么有沒(méi)有什么辦法來(lái)實(shí)現(xiàn)與重載相似的效果呢?有,當(dāng)然有,那就是參數(shù)集(Parameters Set)
PowerShell自定義函數(shù)的參數(shù)集是可以為一個(gè)函數(shù)定義一個(gè)參數(shù)集,在調(diào)用函數(shù)時(shí)可以從參數(shù)集中選擇一個(gè)參數(shù)進(jìn)行使用。注意,只能從參數(shù)集中選擇一個(gè)來(lái)使用。先看看這個(gè)示例,對(duì)參數(shù)集好有一個(gè)感性的認(rèn)識(shí)。
function Add-User
{
[CmdletBinding(DefaultParameterSetName='A')]
param
(
[Parameter(ParameterSetName='A',Mandatory=$true)]
$Name,
[Parameter(ParameterSetName='B',Mandatory=$true)]
$SAMAccountName,
[Parameter(ParameterSetName='C',Mandatory=$true)]
$DN
)
$chosen = $PSCmdlet.ParameterSetName
“You have chosen $chosen parameter set.”
}
上面Add-User函數(shù)定義了一個(gè)參數(shù)集,參數(shù)集中有三個(gè)參數(shù):Name、SAMAccountName、DN,可以選擇其中任何一個(gè)使用。但Add-User函數(shù)只能傳一個(gè)參數(shù)。
You have chosen A parameter set.
PS> Add-User -SAMAccountName test
You have chosen B parameter set.
PS> Add-User -DN test
You have chosen C parameter set.
PS> Add-User -DN test -Name test
Add-User : Parameter set cannot be resolved using the specified named parameters.
洪哥再舉個(gè)例子,我們要做一個(gè)函數(shù),想通過(guò)新聞ID或新聞標(biāo)題來(lái)輸出新聞的內(nèi)容。那么應(yīng)該怎么實(shí)現(xiàn)呢?
function Get-NewsContent
{
[CmdletBinding(DefaultParameterSetName='A')]
[Parameter(ParameterSetName='A',Mandatory=$true)]
$NewsID,
[Parameter(ParameterSetName='B',Mandatory=$true)]
$NewsTitle
$chosen = $PSCmdlet.ParameterSetName
If($chosen -eq "A"){
"News Content by NewsID"
}else{
"News Content by NewsTitle"
}
}
關(guān)于PowerShell函數(shù)支持重載嗎,本文就介紹這么多,希望對(duì)您有所幫助,謝謝!
相關(guān)文章
Windows Powershell 自定義控制臺(tái)
這篇文章主要介紹了Windows Powershell 自定義控制臺(tái),包括選項(xiàng)、字體、布局和顏色四個(gè)方面的自定義風(fēng)格,希望對(duì)大家有所幫助2014-08-08PowerShell多線(xiàn)程執(zhí)行前后臺(tái)作業(yè)的例子
使用后臺(tái)作業(yè)執(zhí)行多個(gè)任務(wù)從先前的技巧中看不是非常高效,它在處理每個(gè)后臺(tái)作業(yè)返回結(jié)果時(shí)將會(huì)浪費(fèi)很多性能。一個(gè)更有效的方法是使用進(jìn)程內(nèi)的任務(wù)。他能分別單獨(dú)的執(zhí)行任務(wù)與Powershell類(lèi)似,所以它不是按順序返回值的2014-04-04Windows Powershell Foreach 循環(huán)
Foreach-object 為cmdlet命令,使用在管道中,對(duì)管道結(jié)果逐個(gè)處理,foreach為遍歷集合的關(guān)鍵字。2014-10-10PowerShell腳本實(shí)現(xiàn)添加、修改任務(wù)計(jì)劃的例子
這篇文章主要介紹了PowerShell腳本實(shí)現(xiàn)添加、修改任務(wù)計(jì)劃的例子,PowerShell操作、設(shè)置任務(wù)計(jì)劃實(shí)例,需要的朋友可以參考下2014-08-08探索PowerShell(十) 循環(huán)語(yǔ)句介紹
本節(jié)所要討論的內(nèi)容的實(shí)質(zhì)更多的偏向于程序設(shè)計(jì)方面,所以在此不做過(guò)多詳細(xì)講解,只針對(duì)PowerShell中的應(yīng)用進(jìn)行具體講解2012-12-12PowerShell腳本開(kāi)發(fā)之收發(fā)UDP消息包
上篇文章我們介紹了使用PowerShell收發(fā)TCP消息包,今天我們來(lái)介紹下使用Powershell收發(fā)UDP小細(xì)胞的方法2014-10-10PowerShell獲取Windows用戶(hù)列表、用戶(hù)信息的方法
這篇文章主要介紹了PowerShell獲取Windows用戶(hù)列表、用戶(hù)信息的方法,一個(gè)簡(jiǎn)單的入門(mén)例子,需要的朋友可以參考下2014-08-08