Ok, so I discovered (the hard way) how functions sort of queue up any output from within the function and then return all of it as part of the return object.
function foo () { echo "SettingVar" $var = "varValue" echo "VarSet" return $var } > foo SettingVar varValue VarSet
I initially found this to be idiotic. Why wouldn’t it behave the same as the rest of the code? Why wouldn’t it behave the same as most other languages that I’ve ever worked with? It made no sense to me.
This makes it much more difficult to take a block of code I suddenly find myself needing to reuse and just throw a function declaration and some brackets around it and reuse it. Suddenly the code has to be refactored to capture all output (or direct to something like Write-Host instead of standard output - which results in its own challenges) in order to avoid ruining the returning object.
But I tried to be open minded. Ok, maybe if they were trying to pseudo-recreate VBScript mechanics (function means return value;subroutine means no return) and this behavior was being used in a ‘subroutine’ to have it return all output at the end, then maybe I could understand it. But since they don’t distinguish between the two and, in fact, eliminated the distinction - only having functions (as far as I’m aware), that doesn’t apply here.
I’ve tried thinking of various ways in which this would be a technical requirement - something structural that prevents these from behaving as just another section in the main line of the code run - after all, it already shares variable scope with the rest of the code in a script, why would it then seem to “jump out” to execute as almost a separate run of code? But with my limited knowledge of the internals of Powershell, I couldn’t come up with anything.
I don’t understand it.
So I would appreciate it if anyone could help me understand why this is the behavior - is it a technical requirement? - and whether there is any possibility of this changing at any point - so that a function (or - to preserve legacy behavior - even create a new thing like a ‘runblock’ or ‘execblock’) would run within the current execution stream, output returns at exec time, not queued up until end of exec, and returning an obj only returns that obj.
Thank you