功能参数检查

时间:2013-04-05 13:30:21

标签: function powershell

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

1 个答案:

答案 0 :(得分:3)

这将为你做检查:

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" 
    } 
}
相关问题