PowerShell: Function Return Value and Statement
Return value
- Anything in function body that isn't captured is returned.
- Captured means assigned to a variable or redirected. 〔see PowerShell: Suppress Command Output〕
- When there are multiple outputs, they are collected in a array as return value.
- if no output, return value is
$null
.
# demo, of a function, anything not captured is returned. # when there are multiple outputs, they are collected in a array as return value. function ff { "something"; 4; } # call $x = ff $x # something # 4 # return type is array, because there are multiple outputs $x.gettype().name # Object[]
# suppress an output function ff { "something"; # suppress an output $null = 4; } # call $x = ff $x # something # return type is string $x.gettype().name # String
Return statement
- function can contain return statement with
return expression
or justreturn
. return
means the function exit at that point.return
does not suppress previous outputs.
function ff { 3; return 4; 5; } # call $x = ff $x # 3 # 4 # return type is array $x.gettype().name # Object[]