Powershell 使用其他参数值验证参数值
我试图在运行函数之前验证路径是否存在。 文件夹路径没有默认值,但文件名默认值应为Powershell 使用其他参数值验证参数值,powershell,powershell-4.0,Powershell,Powershell 4.0,我试图在运行函数之前验证路径是否存在。 文件夹路径没有默认值,但文件名默认值应为template.csv。是否有方法通过ValidateScript属性基于另一个参数值验证参数值 下面的代码返回未设置变量$TemplateDir的错误。我也不完全确定它是否会测试默认的文件名值 function get-Template { [CmdletBinding()] Param ( [Parameter(Mandatory = $true, Position = 0
template.csv
。是否有方法通过ValidateScript属性基于另一个参数值验证参数值
下面的代码返回未设置变量$TemplateDir的错误。我也不完全确定它是否会测试默认的文件名值
function get-Template {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateScript({Test-Path $_})]
[string]$TemplateDir,
[Parameter(Mandatory = $false)]
[ValidateScript({Test-Path ($TemplateDir + "\" + $_)})]
[string]$TemplateFile = "template.csv"
)
...
}
有什么建议吗?您可以使用
DynamicParam
块设置一个动态参数,该参数取决于另一个必需参数的值:
function Get-FilePath
{
Param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidateScript({Test-Path $_})]
[string]$TemplateDir
)
DynamicParam {
# Set up parameter attribute
$fileParamAttribute = New-Object System.Management.Automation.ParameterAttribute
$fileParamAttribute.Position = 3
$fileParamAttribute.Mandatory = $false
$fileParamAttribute.HelpMessage = "Please supply a file name"
# Set up ValidateSet param with actual file name values
$fileValidateParam = New-Object System.Management.Automation.ValidateSetAttribute @(Get-ChildItem $TemplateDir -File |Select-Object -ExpandProperty Name)
# Add the parameter attributes to an attribute collection
$attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($fileParamAttribute)
$attributeCollection.Add($fileValidateParam)
# Create the actual $TemplateFile parameter
$fileParam = New-Object System.Management.Automation.RuntimeDefinedParameter('TemplateFile', [string], $attributeCollection)
# Push the parameter(s) into a parameter dictionary
$paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add('TemplateFile', $fileParam)
# Return the dictionary
return $paramDictionary
}
begin{
# Check if a value was supplied, otherwise set it
if(-not $PSBoundParameters.ContainsKey('TemplateFile'))
{
$TemplateFile = 'template.csv'
}
$myPath = Join-Path $TemplateDir -ChildPath $TemplateFile
}
end {
return $myPath
}
}
这还将为-TemplateFile
您可以通过感谢@mathias-r-jessen阅读更多关于
DynamicParam
的信息!非常有洞察力(对于PS新手来说)。为什么要包含begin{}和end{}块?我在代码中提出了一些小建议。最重要的是,当提供了有效的文件名时,$TemplateFile
var没有被填充,因此返回路径不完整。我无法让ValidateSet和tab完成工作<代码>-TemplateFile在我提供-TemplateDir
后隐藏,无自动制表符完成。然而,它运行良好。。。最后,现在不测试默认文件名。我可以在begin{}
块中轻松地测试这一点,但我认为最合适的方法是通过ValidateScript,在这里我还测试Dir路径。这是可能的吗?这些文件被拒绝了,偏离了你的初衷(?)。遗憾的是,信息非常少,希望您能提供反馈。干杯