あなたは、他の必須パラメータの値に依存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
にしますDynamicParam
について詳しくはGet-Help about_Functions_Advanced_Parameters
ありがとう@ mathias-r-jessen!非常に洞察力のある(PSでかなり新しい人のために)。 begin {}ブロックとend {}ブロックを含める理由は何ですか? – G684
あなたのコードでマイナーな提案をしました。最も重要なのは、有効なファイル名が与えられたときに '$ TemplateFile' varにデータが格納されていないため、戻りパスが不完全であることです。私はValidateSetとタブの補完がうまくいかなかった。 '-TemplateFile'は' -TemplateDir'を提供すると隠され、自動タブ補完はありません。しかし、正常に動作します...最後に、デフォルトのファイル名は現在テストされていません。私は 'begin {}'ブロックでこれを簡単にテストすることができますが、最も適切な方法はValidateScriptを使うことだと思っていました。ここで私はDirパスもテストします。これは可能ですか? – G684
[編集](http://stackoverflow.com/review/suggested-edits/12511640)は、元の意図(?)から逸脱して拒否されました。残念ながら情報がほとんどありませんが、あなたのフィードバックに感謝します。乾杯 – G684