gpt4 book ai didi

powershell - PowerShell 中的动态参数问题

转载 作者:行者123 更新时间:2023-12-02 03:55:14 25 4
gpt4 key购买 nike

动态参数有问题:

function get-foo {
[cmdletBinding()]
param(
[parameter(Mandatory=$true)]
$Name
)
DynamicParam {
if($Name -like 'c*') {
$Attributes = New-Object 'Management.Automation.ParameterAttribute'
$Attributes.ParameterSetName = '__AllParameterSets'
$Attributes.Mandatory = $false
$AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]'
$AttributesCollection.Add($Attributes)
$Dynamic = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern','system.object',$AttributeCollection)
$ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary'
$ParamDictionary.Add("pattern", $Dynamic)
$ParamDictionary
}
}
end {
if($test) {
return $Name -replace '\b\w',$test
}
$name
}
}

它正在检测我的模式参数,但返回错误;

ps c:\> get-foo -Name cruze -pattern 123
get-foo : Le paramètre « pattern » ne peut pas être spécifié dans le jeu de paramètres « __AllParameterSets 
».
Au niveau de ligne : 1 Caractère : 8
+ get-foo <<<< -Name cruze -pattern u
+ CategoryInfo : InvalidArgument: (:) [get-foo], ParameterBindingException
+ FullyQualifiedErrorId : ParameterNotInParameterSet,get-foo

如何解决这个问题?

最佳答案

$AttributeCollection 替换为 $AttributesCollection(缺少“s”)。

使用 Set-StrictMode 来捕获此类拼写错误 :)


至于剧本,我觉得还有其他问题。这是更正后的工作版本:

function get-foo {
[cmdletBinding()]
param(
[parameter(Mandatory=$true)]
$Name
)
DynamicParam {
if ($Name -like 'c*') {
$Attributes = New-Object 'Management.Automation.ParameterAttribute'
$Attributes.ParameterSetName = '__AllParameterSets'
$Attributes.Mandatory = $false
$AttributesCollection = New-Object 'Collections.ObjectModel.Collection[Attribute]'
$AttributesCollection.Add($Attributes)
$Pattern = New-Object -TypeName 'Management.Automation.RuntimeDefinedParameter' -ArgumentList @('pattern', [string], $AttributesCollection)
$ParamDictionary = New-Object 'Management.Automation.RuntimeDefinedParameterDictionary'
$ParamDictionary.Add("pattern", $Pattern)
$ParamDictionary
}
}
end {
if ($Name -like 'c*') {
if ($Pattern.IsSet) {
return $Name -replace '\b\w', $Pattern.Value
}
}
$name
}
}

关于powershell - PowerShell 中的动态参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12951972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com