ChatGPT解决这个技术问题 Extra ChatGPT

Function return value in PowerShell

I have developed a PowerShell function that performs a number of actions involving provisioning SharePoint Team sites. Ultimately, I want the function to return the URL of the provisioned site as a String so at the end of my function I have the following code:

$rs = $url.ToString();
return $rs;

The code that calls this function looks like:

$returnURL = MyFunction -param 1 ...

So I am expecting a String, however it's not. Instead, it is an object of type System.Management.Automation.PSMethod. Why is it returning that type instead of a String type?

Can we see the function declaration?
No, not the function invocation, show us how/where you declared "MyFunction". What happens when you do: Get-Item function:\MyFunction
Suggested an alternate way to address this : stackoverflow.com/a/42842865/992301
I think this is one of the most important PowerShell questions on stack overflow relating to functions/methods. If you're planning on learning PowerShell scripting you should read this entire page and understand it thoroughly. You'll hate yourself later if you don't.
using static class-functions seems to me the proper clean solution as in this answer: stackoverflow.com/a/42743143/1915920

G
Goyuix

PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:

All output is captured, and returned

The return keyword really just indicates a logical exit point

Thus, the following two script blocks will do effectively the exact same thing:

$a = "Hello, World"
return $a

$a = "Hello, World"
$a
return

The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).

Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.

It is also worth noting that you probably don't need those semicolons - unless you are nesting multiple expressions on a single line.

You can read more about the return semantics on the about_Return page on TechNet, or by invoking the help return command from PowerShell itself.


so is there any way to return a scaler value from a function?
If your function returns a hashtable, then it will treat the result as such, but if you "echo" anything within the function body, including the output of other commands, and suddenly the result is mixed.
If you want to output stuff to the screen from within a function without returning that text as part of the function result, use the command write-debug after setting the variable $DebugPreference = "Continue" instead of "SilentlyContinue"
This helped, but this stackoverflow.com/questions/22663848/… helped even more. Pipe unwanted results of commands/function calls in the called function via " ... | Out-Null" and then just return the thing you want.
@LukePuplett echo was the issue for me! That little side point is very very important. I was returning a hashtable, following everything else, but still the return value was not what I expected. Removed the echo and worked like a charm.
P
Peter Mortensen

This part of PowerShell is probably the most stupid aspect. Any extraneous output generated during a function will pollute the result. Sometimes there isn't any output, and then under some conditions there is some other unplanned output, in addition to your planned return value.

So, I remove the assignment from the original function call, so the output ends up on the screen, and then step through until something I didn't plan for pops out in the debugger window (using the PowerShell ISE).

Even things like reserving variables in outer scopes cause output, like [boolean]$isEnabled which will annoyingly spit a False out unless you make it [boolean]$isEnabled = $false.

Another good one is $someCollection.Add("thing") which spits out the new collection count.


Why would you just reserve a name instead of doing the best practice of properly initializing the variable with a value explicitly defined.
I take it you mean that you have a block of variable declarations at the start of each scope for every variable used in that scope. You should still, or may already, be initializing all variables before using them in any language including C#. Also importantly doing [boolean]$a in powershell does not actually declare the variable $a. You can confirm this by following that line with the line $a.gettype() and compare that output to when you declare and initialize with the string $a = [boolean]$false.
You're probably right, I'd just prefer a more explicit design to prevent accidental writes.
Coming from a programmer's perspective, although I'm a PS-n00b, I am not so sure I find this the very worst of the many annoying aspects of PS syntax. How on earth did anyone think it preferable to write "x -gt y" rather than "x > y"?!? Surely at least the built-in operators could have used a more human-friendly syntax?
@TheDag because it's a shell first, programming language second; > and < are already used for I/O stream redirection to/from files. >= writes stdout to a file called =.
P
Peter Mortensen

With PowerShell 5 we now have the ability to create classes. Change your function into a class, and return will only return the object immediately preceding it. Here is a real simple example.

class test_class {
    [int]return_what() {
        Write-Output "Hello, World!"
        return 808979
    }
}
$tc = New-Object -TypeName test_class
$tc.return_what()

If this was a function the expected output would be

Hello World
808979

but as a class the only thing returned is the integer 808979. A class is sort of like a guarantee that it will only return the type declared or void.


Note. It also supports static methods. Leading to the syntax [test_class]::return_what()
"If this was a function the expected output would be 'Hello World\n808979" -- I don't think that's correct? The output value is always only the value of the last statement, in your case return 808979, function or not.
@amn Thank you! You are very correct the example would only return that if it created output within the function. Which is what annoys me. Sometimes your function may generate output and that output plus any value you add in the return statement gets returned. Classes as you know will only return the type declared or void. If you rather use functions then one easy method is to assign the function to a variable and if more than the return value is returned the var is an array and the return value will be the last item in the array.
Well, what do you expect from a command called Write-Output? It's not the "console" output that is referred to here, it's the output for the function/cmdlet. If you want to dump stuff on the console there are Write-Verbose, Write-Host and Write-Error functions, among others. Basically, Write-Output is closer to the return semantics, than to a console output procedure. Don't abuse it, use Write-Verbose for verbosity, that's what it's for.
@amn I am very aware this is not the console. It was mealy a quick way to show the way a return deals with unexpected output inside a function vs a class. in a function all output + the value you return are all passed back. HOWEVER only the value specified in the return of a class is passed pack. Try running them for yourself.
X
XDS

As a workaround I've been returning the last object in the array that you get back from the function... It is not a great solution, but it's better than nothing:

someFunction {
   $a = "hello"
   "Function is running"
   return $a
}

$b = someFunction
$b = $b[($b.count - 1)]  # Or
$b = $b[-1]              # Simpler

All in all, a more one-lineish way of writing the same thing could be:

$b = (someFunction $someParameter $andAnotherOne)[-1]

$b = $b[-1] would be a simpler way of getting the last element or the array, but even simpler would be to just not output values you don't want.
@Duncan And what if I do want to output the stuff in the function, while at the same time I also want a return value?
@ThoAppelsin if you mean you want to write stuff to the terminal then use write-host to output it directly.
P
Peter Mortensen

I pass around a simple Hashtable object with a single result member to avoid the return craziness as I also want to output to the console. It acts through pass by reference.

function sample-loop($returnObj) {
  for($i = 0; $i -lt 10; $i++) {
    Write-Host "loop counter: $i"
    $returnObj.result++
  }
}

function main-sample() {
  $countObj = @{ result = 0 }
  sample-loop -returnObj $countObj
  Write-Host "_____________"
  Write-Host "Total = " ($countObj.result)
}

main-sample

You can see real example usage at my GitHub project unpackTunes.


S
StingyJack

The existing answers are correct, but sometimes you aren't actually returning something explicitly with a Write-Output or a return, yet there is some mystery value in the function results. This could be the output of a builtin function like New-Item

PS C:\temp> function ContrivedFolderMakerFunction {
>>    $folderName = [DateTime]::Now.ToFileTime()
>>    $folderPath = Join-Path -Path . -ChildPath $folderName
>>    New-Item -Path $folderPath -ItemType Directory
>>    return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result


    Directory: C:\temp


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/9/2020   4:32 PM                132257575335253136
True

All that extra noise of the directory creation is being collected and emitted in the output. The easy way to mitigate this is to add | Out-Null to the end of the New-Item statement, or you can assign the result to a variable and just not use that variable. It would look like this...

PS C:\temp> function ContrivedFolderMakerFunction {
>>    $folderName = [DateTime]::Now.ToFileTime()
>>    $folderPath = Join-Path -Path . -ChildPath $folderName
>>    New-Item -Path $folderPath -ItemType Directory | Out-Null
>>    # -or-
>>    $throwaway = New-Item -Path $folderPath -ItemType Directory 
>>    return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
True

New-Item is probably the more famous of these, but others include all of the StringBuilder.Append*() methods, as well as the SqlDataAdapter.Fill() method.


Or Out-Default if you do want to display it but don't want it to go the return value.
S
Shay Levy

It's hard to say without looking at at code. Make sure your function doesn't return more than one object and that you capture any results made from other calls. What do you get for:

@($returnURL).count

Anyway, two suggestions:

Cast the object to string:

...
return [string]$rs

Or just enclose it in double quotes, same as above but shorter to type:

...
return "$rs"

Or even just "$rs" - the return is only required when returning early from the function. Leaving out the return is better PowerShell idiom.
P
Peter Mortensen

Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.

To get around this issue I've been using global variables rather than returning and using the value from the function call.

Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function


P
Peter Mortensen

The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.

Function StartingMain {
  $a = 1 + 3
  $b = 2 + 5
  $c = 3 + 7
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b
}

StartingEnd(StartingMain)

This can also be done for an array. The example below will return "Text 2"

Function StartingMain {
  $a = ,@("Text 1","Text 2","Text 3")
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b[1]
}

StartingEnd(StartingMain)

Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.


3
3lvinaz

You need to clear output before returning. Try using Out-Null. That's how powershell return works. It returns not the variable you wanted, but output of your whole function. So your example would be:

function Return-Url
{
   param([string] $url)

   . {
       $rs = $url.ToString();
       return
   } | Out-Null
   
   return $rs
}

$result = Return-Url -url "https://stackoverflow.com/questions/10286164/function-return-value-in-powershell"

Write-Host $result
Write-Host $result.GetType()

And result is:

https://stackoverflow.com/questions/10286164/function-return-value-in-powershell
System.String

Credits to https://riptutorial.com/powershell/example/27037/how-to-work-with-functions-returns