Return Keyword in PowerShell
In Standard PowerShell
the Return keyword exits the current scope. Return also returns the associated object . the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the return keyword.
In Classes
The Return keyword works very differently in methods in PowerShell classes. It works like the Return statements in other languages, including C#.
In a class method, the Return keyword:
- Exits the current scope.
- Returns the associated object (return ).
- Returns ONLY the associated object. It prevents the method from returning anything else.
- The object that Return returns must match the return type of the method.
- A return statement with no return type is a syntax error.
- A return type with no return statement is a syntax error.
- Returning a different type from the return statement is a runtime error.
If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the Information stream. The code below corrects the above example using the Write-Information cmdlet with a InformationAction of Continue.
So, the Return keyword behaves very differently in classes than it does in standard PowerShell.
When PowerShell was being developed, the team wanted to make it very simple to use and they thought that the standard Return was easier. But, it was so confusing to people who know Return from other languages, that they realized they had made a mistake. The implementation in classes is an attempt to rectify that mistake.