我正在 Powershell 中實作一個函式,它將執行 REST 呼叫。根據給定的場景,其中一個引數的內容可能不同。例如,body該的REST呼叫可以是字串或哈希表。你如何在CmdletBinding()宣告中實作這一點?
例如
Function doRESTcall(){
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Hashtable]$headers
[Parameter(Mandatory=$true)]
[???????]$body # what type here??
)
.
.
.
}
uj5u.com熱心網友回復:
要宣告允許任何型別的引數,您可以根本不對引數進行型別約束,也可以使用型別約束[object]( System.Object ),這樣做不需要型別轉換,因為 PowerShell 中的所有物件都繼承自該型別。
值得一提的是,不受約束的引數將允許$null作為引數,以避免這種情況,[ValidateNotNull()]和/或[parameter(Mandatory)]可以使用。
function Test-Type {
param(
[parameter(ValueFromPipeline, Mandatory)]
[object]$Value
)
process
{
[pscustomobject]@{
Type = $Value.GetType().FullName
IsObject = $Value -is [object]
}
}
}
PS /> 1, 'foo', (Get-Date) | Test-Type
Type IsObject
---- --------
System.Int32 True
System.String True
System.DateTime True
uj5u.com熱心網友回復:
解決這個問題的正確方法是創建一個ParameterSet:
Function doRESTcall(){
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ParameterSetName = 'StringBody', Position = 0)]
[Parameter(Mandatory=$true, ParameterSetName = 'HashBody', Position = 0)]
[Hashtable]$headers,
[Parameter(Mandatory=$true, ParameterSetName = 'StringBody', Position = 1)]
[String]$Stringbody,
[Parameter(Mandatory=$true, ParameterSetName = 'HashBody', Position = 1)]
[Hashtable]$Hashbody
)
Write-Host 'Parameter set:' $PSCmdlet.ParameterSetName
Write-Host 'StringBody:' $StringBody
Write-Host 'HashBody:' $HashBody
}
doRESTcall -?
NAME
doRESTcall
SYNTAX
doRESTcall [-headers] <hashtable> [-Hashbody] <hashtable> [<CommonParameters>]
doRESTcall [-headers] <hashtable> [-Stringbody] <string> [<CommonParameters>]
ALIASES
None
REMARKS
None
doRESTcall @{a = 1} 'Test'
Parameter set: StringBody
StringBody: Test
HashBody:
注意:為了接受更多種類的字典(如[Ordered]),我將使用[System.Collections.Specialized.OrderedDictionary](而不是[Hashtable])型別作為相關引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399975.html
