Your PowerShell script could return something totally different from what you would have thought. Considering below function/script:
function demo-returnValues {
"1"
"2"
return [string]"3"
}
$dn = demo-returnValues
write-host "return Type: $($dn.gettype().fullname)"
write-host "element count $($dn.count)"
write-host " Values:"
$dn|foreach {write-host "[[$_]]"}
It doesn't return a string of value "3"! Rather it returns an array of 3 elements. See its output:
return Type: System.Object[]element count 3Values:[[1]][[2]][[3]]
This is because anything within a function that emits value that are not caught will be added to a pipeline. What you intend to return is also added to this pipeline. Finally it is this pipeline that gets returned.
To fix this, you can do one of below 3
- Assigned to variable
- Suppressed by [void]
- piped to out-null
Revised function below. This returns only a string of "4"
function demo-returnValues {
[void]"1"
$uselessVar = "2"
"3" | out-null
return [string]"4"
}