powershell - Function parameters check -
i'm writing basic powershell libraries, , need check if specific parameter in group of values.
in example define function alv_time optional parameter. if defined, have 2 values, else signal warning. works, correct way allow parameter values or there standard way?
$warningcolor = @{"foregroundcolor" = "red"} function avl_time { [cmdletbinding()] param ( $format ) process { # format parameter if ($format) { # list format possible parameters $format_parameters = @("short: date", "long: date , 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 parameters:" $format_parameters | foreach { write-host @warningcolor "$_" } } } # without format parameter else { $now = get-date -format "yyyy-mm-dd" } # return time return $now } }
this check you:
param( [validateset("short","long")] [string] $format )
example script more validations:
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" } }
Comments
Post a Comment