函数参数检查

问题描述:

我在写一些基本的powershell库,我需要检查一个特定的参数是否在一组值中。函数参数检查

在这个例子中,我定义了一个带有可选参数的函数ALV_time。如果定义,它可能只有2个值,否则我发出警告。它可以工作,但是这是仅允许一些参数值的正确方法,还是存在标准方法?

$warningColor = @{"ForegroundColor" = "Red"} 

function AVL_Time { 
    [CmdletBinding()] 
    param (
     $format 
    ) 

    process { 
     # with format parameter 
     if ($format) { 
      # list format possible parameters 
      $format_parameters = @("short: only date", "long: date and time") 
      if ($format -like "short") { 
       $now = Get-Date -Format "yyyy-MM-dd" 
      } 
      # long date 
      elseif ($format -like "long") { 
       $now = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 
      } 
      # if wrong format parameter 
      else { 
       Write-Host @warningColor "Please use only those parameters:" 
       $format_parameters | foreach { 
        Write-Host @warningColor "$_" 
       } 
      } 
     } 
     # without format parameter 
     else { 
      $now = Get-Date -Format "yyyy-MM-dd" 
     } 

     # return time 
     return $now 
    } 
} 

这将做检查为您提供:

Param( 
     [ValidateSet("short","long")] 
     [String] 
     $format) 

示例脚本更加验证:

Function Foo 
{ 
    Param( 
     [ValidateSet("Tom","Dick","Jane")] 
     [String] 
     $Name 
    , 
     [ValidateRange(21,65)] 
     [Int] 
     $Age 
    , 
     [ValidateScript({Test-Path $_ -PathType 'Container'})] 
     [string] 
     $Path 
    ) 
    Process 
    { 
     "Foo $name $Age $path" 
    } 
}