- Joined
- Oct 20, 2019
It returns "OK" or "Cancel" depending on what the user selects, followed by the file name. The reason for this is because a Powershell script is essentially just a sequence of commands the same as if you typed them in a terminal. If you'd typedwhat does this return?
Code:function getfile(){ $location = New-Object System.Windows.Forms.OpenFileDialog $location.initialDirectory = $initialDirectory $location.filter = "CSV (*.csv)| *.csv" $location.ShowDialog() return $location.FileName } getfile
$location.ShowDialog() on the command line you would expect to see its return value on the command line. Putting it in a script doesn't change that.Simple example: A string is a valid statement in Powershell. If I wrote "hello" on the command line, I'll just get "hello" back.

Now what happens if I have a script hello.ps1 which is just "hello" ? Well it's the same command giving the same output, that it's in a script doesn't change that. Run the script and get "hello". And if I have the following script:
Code:
"hello"
"hello"
"hello"
Then I get "hello" three times.
And intuitively, if I was assigning the string to a variable, it wouldn't wouldn't output anything.

Now what's going on with your example becomes clearer. ShowDialog() returns a value, just as "hello" would. You're not doing anything with it so it's included in the script's output just as if you were typing these lines one by one in the terminal. To suppress that, you merely capture the output. So you would either assign it to a variable (normal):
$result = $location.ShowDialog() or you can just discard it$location.ShowDialog() | Out-Null.The 'gotcha' is one of assumptions, really. You're presuming that nothing can escape from a function's scope unless explicitly done by a return statement (which is more akin to an exit() in Powershell). But that's not even true in Bash. If a Bash function had lines like
echo "hello" in it, you wouldn't expect them not to be displayed because they weren't part of the return value. In Powershell, you don't need "echo". All statement's outputs are output if not captured.Your original statement was that you can't return values from a Powershell function. That's incorrect. What you mean is that they return things automatically, unless results are directed elsewhere (e.g. into a variable, to Null, whatever). It's a gotcha when learning perhaps, but quickly understood. A Powershell script is the same whether in a single file or typed line by line on the terminal.
Anyway, I thought this was interesting enough to others that I'd answer. It's not meant as part of debate.