1
我想在Powershell中使用動態參數,但參數的值在我運行完腳本後似乎不存在。Powershell - 使用動態參數值
[CmdletBinding()]
Param (
[Parameter(
Mandatory=$true,
Position=0,
HelpMessage = "The entity ID for the Version"
)]
[string]$TPVersionID,
[Parameter(
Mandatory=$true,
Position=1,
HelpMessage = ""
)]
[string]$VersionNumber,
[Parameter(
Mandatory=$true,
Position=2,
HelpMessage = "This is a boolean value; enter any value to make it True, leave it blank to make it False."
)]
[bool]$PullVersionDoc
)
function Get-VersionParam{
[CmdletBinding()]
Param ([string]$TPVersionID, [string]$VersionNumber, [bool]$PullVersionDoc?)
DynamicParam {
if ($PullVersionDoc) {
write-host("HEY!")
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.Position = 3
$attributes.Mandatory = $true
$attributeCollection = new-object `
-Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$dynParam1 = new-object `
-Type System.Management.Automation.RuntimeDefinedParameter('VersionDocumentID', [Int32], $attributeCollection)
$paramDictionary = new-object `
-Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add('VersionDocumentID', $dynParam1)
return $paramDictionary
}
}
}
Get-VersionParam
#Write-Host "Dynamic Parameter PullVersionDoc? = " $PullVersionDoc
Write-Host $PSBoundParameters
我希望腳本索要[VersionDocumentID]如果[PullVersionDoc]布爾值爲TRUE在腳本以後使用,但是當我寫出來的[$ PSBoundParameters]參數沒有按」不存在。我如何獲得價值以便我可以使用它?
'$ a = Get-VersionParam; Write-host $ a' – 4c74356b41
使用'[bool]'參數也沒有意義。改用'[switch]'。通過這種方式,您可以添加參數名稱以使開關爲真或將其關閉,並將其評估爲False。此外,您可以訪問Begin塊中的$ PSBoundParameters [$ ParameterName]並處理Process塊中的項目。 – user4317867
我不確定我是否理解。 'VersionDocumentID'參數只存在於函數內部,除非你在函數體中添加了類似'$ script:VersionDocumentID = $ VersionDocumentID'的東西(或者輸出值並將其存儲爲@ 4c74356b41顯示)。除了要求它從不使用的值之外,你的函數不會執行任何操作。 –