Function 功能参数检查

Function 功能参数检查,function,powershell,Function,Powershell,我正在编写一些基本的powershell库,需要检查特定参数是否在一组值中 在这个例子中,我定义了一个带有可选参数的函数ALV_time。如果定义了,它只能有2个值,否则我会发出警告信号。它可以工作,但这是只允许某些参数值的正确方法还是有标准方法 $warningColor = @{"ForegroundColor" = "Red"} function AVL_Time { [CmdletBinding()] param ( $format )

我正在编写一些基本的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" 
    } 
}