Function return value in PowerShell

2019-01-01 15:21发布

问题:

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?

回答1:

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.



回答2:

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

So, what I do is to remove the assignment from the original function call so the output ends up on screen, and then step through until something I didn\'t plan for pops out in the debugger window (using the PS 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 the new collection count.



回答3:

With PowerShell 5 we now have the ability to create classes. Changing your function in to a class not only can you you can type it and return will ONLY return the object immediately preceding it. Here is a real simple example.

class test_class{
    [int]return_what() {
        $a = \"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 an the INT 808979. A class is sorta like a guarantee that it will only return the type declared or void.



回答4:

As a workaround I\'ve been returning the last object in the array that you get back from the function... 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


回答5:

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



回答6:

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\"


回答7:

Luke\'s description of the function results in these scenarios seems to be right on. Only wish to understand the root cause and the PowerShell product team would do something about the behavior, seems to be quite common and has cost be 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 thread 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



回答8:

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.

I do hope it helps.



标签: powershell