2016-05-29 3 views
0

関数を実行する前にパスが存在するかどうかを検証しようとしています。 フォルダパスの既定値はありませんが、ファイル名の既定値はtemplate.csvです。 ValidateScript属性を使用して、別のパラメータ値に基づいてパラメータ値を検証する方法はありますか?別のパラメータ値を使用してパラメータ値を検証する

以下のコードは、変数$ TemplateDirが設定されていないというエラーを返します。また、デフォルトのファイル名の値をテストするかどうかは完全にはわかりません。

アドバイスはありますか?

答えて

2

あなたは、他の必須パラメータの値に依存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

+0

ありがとう@ mathias-r-jessen!非常に洞察力のある(PSでかなり新しい人のために)。 begin {}ブロックとend {}ブロックを含める理由は何ですか? – G684

+0

あなたのコードでマイナーな提案をしました。最も重要なのは、有効なファイル名が与えられたときに '$ TemplateFile' varにデータが格納されていないため、戻りパスが不完全であることです。私はValidateSetとタブの補完がうまくいかなかった。 '-TemplateFile'は' -TemplateDir'を提供すると隠され、自動タブ補完はありません。しかし、正常に動作します...最後に、デフォルトのファイル名は現在テストされていません。私は 'begin {}'ブロックでこれを簡単にテストすることができますが、最も適切な方法はValidateScriptを使うことだと思っていました。ここで私はDirパスもテストします。これは可能ですか? – G684

+0

[編集](http://stackoverflow.com/review/suggested-edits/12511640)は、元の意図(?)から逸脱して拒否されました。残念ながら情報がほとんどありませんが、あなたのフィードバックに感謝します。乾杯 – G684

関連する問題