Integral types
«Integral types» are passed by value by default.
Function-parameter definition
Optionally, the expected type of the parameter can be specified after
[ref]
, for example
[ref][string]
as shown in the following simple
function declaration.
The value of the parameter that needs to be returned to the caller can then be assigned to the parameter's property .value
:
function demonstrate-passing-by-reference {
param (
[ref][string] $result
)
$result.value = 'value assigned in function'
}
Calling the function
When calling the function, the variable that receives the out value also needs to be declared with the [ref]
type accelerator and enclosed in parantheses, as shown below:
[string] $xyz = ''
demonstrate-passing-by-reference ([ref] $xyz)
write-host "xyz after calling function: $xyz"
Object types
function change-values {
param (
$p
)
$p.txt = 'changed'
$p.num = 99
}
$hash = @{num = 42; txt = 'Hello world'}
$obj = new-object psObject -property @{num = 42; txt = 'Hello world'}
change-values $hash
change-values $obj
write-host "num = $($hash.num), txt = $($hash.txt)"
write-host "num = $($obj.num ), txt = $($obj.txt )"