PowerShell實(shí)現(xiàn)參數(shù)互斥示例
在PowerShell的函數(shù)中如果想讓參數(shù)互斥,可以使用 “ParameterSetName”屬性將一個(gè)parameter屬性定義在不同的參數(shù)或著參數(shù)集合中。
很多人可能沒有留意,在PowerShell的函數(shù)中,我們可以將多個(gè)參數(shù)屬性定義在同一個(gè)參數(shù)名上,這樣配合mandatory可以讓一個(gè)參數(shù)在某個(gè)場景下是強(qiáng)制的,在另外的場景下則是可選的。
function Test-ParameterSet
{
[CmdletBinding(DefaultParameterSetName='NonCredential')]
param
(
$id,
[Parameter(ParameterSetName='LocalOnly', Mandatory=$false)]
$LocalAction,
[Parameter(ParameterSetName='Credential', Mandatory=$true)]
[Parameter(ParameterSetName='NonCredential', Mandatory=$false)]
$ComputerName,
[Parameter(ParameterSetName='Credential', Mandatory=$false)]
$Credential
)
$PSCmdlet.ParameterSetName
$PSBoundParameters
if ($PSBoundParameters.ContainsKey('ComputerName'))
{
Write-Warning '遠(yuǎn)程調(diào)用'
}
}
上面的函數(shù)Test-ParameterSet 將演示在參數(shù)”NonCredential”激活時(shí), -ComputerName為可選參數(shù)。而當(dāng)你使用了 -Credential 參數(shù)時(shí), -ComputerName 就變成了強(qiáng)制參數(shù)。而當(dāng)你使用了 -LocalAction 參數(shù)以后,-ComputerName和-Credential均可有可無。
相關(guān)文章
Windows Powershell IF-ELSEIF-ELSE 語句
作為條件判斷,if語句是各大語言都在使用的,當(dāng)然powershell也不例外,今天我們就來看下IF-ELSEIF-ELSE 語句2014-10-10
PowerShell查看本機(jī)文件關(guān)聯(lián)程序和默認(rèn)打開程序的方法
這篇文章主要介紹了PowerShell查看本機(jī)文件關(guān)聯(lián)程序和默認(rèn)打開程序的方法,本文給出了查看方法,同時(shí)給出了一份讀取結(jié)果,需要的朋友可以參考下2015-06-06
Windows Powershell對(duì)象=屬性+方法
從今天開始,我們這個(gè)系列的教程進(jìn)入到講訴使用對(duì)象的階段,那么本階段的第一篇還是先來熟悉下概念,簡單的說對(duì)象=屬性+方法2014-09-09
在cmd中直接運(yùn)行PowerShell腳本文件的方法
這篇文章主要介紹了在cmd中直接運(yùn)行PowerShell腳本文件的方法,本文給出了兩個(gè)小技巧實(shí)現(xiàn)在cmd中直接運(yùn)行PowerShell腳本,需要的朋友可以參考下2014-12-12
PowerShell小技巧之添加遠(yuǎn)程防火墻規(guī)則
本文主要介紹了將Windows Server 2012 Core的默認(rèn)控制臺(tái)設(shè)置成了PowerShell后,啟用了遠(yuǎn)程桌面,然后使用PowerShell添加PowerShell遠(yuǎn)程防火墻規(guī)則。希望對(duì)大家能有所幫助。2014-09-09

