如何在PowerShell脚本型Cmdlet中实现IValidateSetValuesGenerator?
解决方案
方法一:调整类定义位置(推荐)
PowerShell脚本型Cmdlet的要求是[CmdletBinding()]必须在param()之前,并非param()必须是脚本首行。你可以先定义验证类,再声明Cmdlet属性和参数,这样既满足动态ValidateSet需求,又无需额外预操作:
# 定义动态验证集生成类 Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator { [string[]] GetValidValues() { # 替换为你的目标目录路径,返回txt文件名(不含扩展名用BaseName,含扩展名用Name) return (Get-ChildItem -Path 'C:\YourTargetDirectory' -Filter '*.txt').BaseName } } # 声明Cmdlet属性 [CmdletBinding()] param( [Parameter(Mandatory)] [ValidateSet([SoundNames])] [string]$SoundName ) # 后续脚本逻辑示例 Write-Host "你选择的文件是: $SoundName"
方法二:强制以param()开头时用动态参数
如果你的场景要求脚本必须以param()作为首行,可以用动态参数实现同样的效果,无需提前定义类:
[CmdletBinding()] param() DynamicParam { # 指定目标目录 $targetDir = 'C:\YourTargetDirectory' # 获取目录下所有txt文件的名称 $validFileNames = (Get-ChildItem -Path $targetDir -Filter '*.txt').Name # 创建参数属性 $paramAttr = [System.Management.Automation.ParameterAttribute]@{ Mandatory = $true Position = 0 } # 创建验证集属性 $validateSetAttr = [System.Management.Automation.ValidateSetAttribute]::new($validFileNames) # 组合属性集合 $attrCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new() $attrCollection.Add($paramAttr) $attrCollection.Add($validateSetAttr) # 创建动态参数 $dynParam = [System.Management.Automation.RuntimeDefinedParameter]::new( 'SoundName', # 参数名 [string], # 参数类型 $attrCollection ) # 返回动态参数字典 $paramDict = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() $paramDict.Add('SoundName', $dynParam) return $paramDict } begin { # 将动态参数的值赋值给变量,方便后续使用 $SoundName = $PSBoundParameters['SoundName'] } process { # 脚本逻辑示例 Write-Host "选中的文件: $SoundName" }
说明
- 两种方法都是独立脚本,无需预先点源其他文件或在会话中预定义类型
- 替换代码中的
C:\YourTargetDirectory为你实际的目标目录即可 - 如果需要参数接受带扩展名的文件名,把
BaseName改为Name即可
内容的提问来源于stack exchange,提问作者joeking
相关产品推荐
相关产品推荐

