How workaround function() lack of return value specification?


Trying to find out what is the best way to design script with reusable functions without running into possibility accidentally writing into output by forgetting | Out-Null statements etc?

Pretty much, “don’t do that.” The language doesn’t offer any inbuilt protections, except in v5 classes.

“Dont’ do that”? What do you mean? Don’t use functions? How do you reuse code properly? Global variables instead? Or what is a guidance?

Sorry - just “don’t” accidentally output stuff you don’t want output. “Don’t” forget to use Out-Null. That’s the guidance. There is no way, aside from v5 classes, to design [a] script with reusable functions without running into the possibility [of] accidentally writing into output. PowerShell just doesn’t offer any physical means of doing so. It’s irritating sometimes, and it’s something that v5 classes, with their stricter “return” keyword, address, but in terms of functions or the rest of the language, there’s nothing you can do to address the situation. I’m not actually trying to be snarky - it’s just that there’s nothing to do, apart from “be really, really careful when you code.”

I suppose if you really wanted to, you could write a function like this:

function Do-Something
    $return = $null
    $null = & {
        # stuff
        $return = 'Value to return'
        # more stuff

    return $return

It’s funny looking, but that would guarantee that anything you didn’t explicitly assign to the $return variable wouldn’t go down the pipeline.

I’m wondering why this feature was omitted from original Powershell specification. Even novice programmers would expect to be available to return specific type from Function()

Mostly because it’s trying to be both a shell and a scripting language. Some of the shell semantics are really awkward for people who are thinking like a developer (and that’s why classes, more of a developer thing anyway, behave differently.)