PowerShell Function Return

Most PowerShell newbies believe that PowerShell functions can return a value only through the Return statement. The return statement usually terminates the function and returns control to the calling code block. But in Windows PowerShell, this is not entirely true…

In this article, we will take a look at how to return values from PowerShell functions using the Return command.

The Return command in PowerShell is used if a function is in order to terminate the function and return back to the caller scope or return a value from a function.

In traditional programming languages, functions usually return a single value of a particular type, but in Windows PowerShell, the results of the function are sent to the output stream.

Let’s look at the simplest PowerShell function:

function TestReturn($param) {

$x = $param + 5

"text"

2*2

return $x

}

If you run this function with a parameter 5 (TestReturn (5)) in a classical programming language, such construction should return 10 (integer value).

However, in case of PowerShell, we will see the output:

text

4

10

powershell function return value

As you can see, the PowerShell function returned 3 values as a result. That’s why the Return command in PowerShell isn’t particularly well understood.

The Microsoft PowerShell reference doc says that the return keyword exits the current scope, which can be a function, script, or script block.

In other words, it is used to complete the execution of a function code and transfer control to the parent block. If you add any parameter to the return statement, this value will be returned to the calling code block, and return value.

Note. It is not necessary to specify a Return command in a PowerShell function. The value of any variable or object that is displayed directly in the body of the function will be available as the function output.

You can assign the value of the function to a variable and check its type with the following commands:

$MyTestVar=TestReturn (5)

$MyTestVar.GetType().FullName

The return type of the function is System.Object [], i.e. this is an array. If the output of the function contains objects, the returned object instances will also fall into the collection (dynamic array).

You can display the length of the array and the values contained in it:

$MyTestVar.length

$MyTestVar[0]

$MyTestVar[1]

$MyTestVar[2]

powershell function return

By default, PowerShell functions work in a such way that when executed they write all the values that were displayed during the function’s operation to the $Result array. This is not always convenient when writing PowerShell functions.

In order not to send extra values to the output stream of the function, don’t use the echo (an alias for the Write-Output cmdlet) to write debugging info in your PowerShell scripts. Instead, use the following cmdlets: Write-Host, Write-Verbose, or Write-Debug cmdlets. These cmdlets will output function data to the console (on the screen), and not to the function output stream:

function TestReturn($param) {

$x = $param + 5

Write-Host "text"

Write-Host 2*2

return $x

}

$MyTestVar = TestReturn (5)

$MyTestVar

As you can see, the function returned only the value that we expected — 10.

powershell return value from function

You can also hide extra information from the output stream using the Return statement (it resembles the Break command in PowerShell loops). Then you use Return, which stops the function and returns a value.

function TestReturn($param) {

“This line is displayed”

return

“ This line is not displayed”

}

$MyTestVar = TestReturn (5)

$MyTestVar

powershell return value

In this example, the return keyword terminates the current function (exits the current scope). This means that line 4 is not processed and therefore not displayed.

There is one more peculiarity of using Return statement in functions. In PowerShell, the scope of variables in a function is limited. All variables created inside the function remain in it. With Return, you can return the values of variables outside of the function:

function Get-LastLog ($param1) {

$newevents = Get-EventLog -LogName System -Newest $param1

return $newevents

}

$result = Get-DayLog -5

$result

There can be multiple return values in the function.

function Get-FolderSize ($Path) {

$FullSizeMb="{0:N2} MB" -f ((gci –force $Path –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Mb)

$FirstLevelSizeMb ="{0:N2} MB" -f ((gci –force $Path -ErrorAction SilentlyContinue| measure Length -s).sum / 1Mb)

return $FullSizeMb, $FirstLevelSizeMb

}

Get-FolderSize “C:\PS”

powershell function return string

The Return cmdlet can be used in If-Else statements:

function Get-FolderSize {

$FullSizeMb="{0:N2} MB" -f ((gci –force $Path –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Mb)

if $FullSizeMb -gt 1000) {

return "Large Folder" + $FullSizeMb}

else{

return "Small Folder" + $FullSizeMb}

}

Get-FolderSize “C:\PS”
I enjoy technology and developing websites. Since 2012 I'm running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
Cyril Kardashevsky

One comment

  1. Hi please help me with this code i am always getting a failed results.

    $files = Get-Content C:\temp\test\info.txt

    foreach($file in $files)
    {

    $sourcePath = “C:\temp\test\source\” + $file
    $destinationpath = “C:\temp\test\destination”

    function check()
    {
    Copy-Item $sourcePath $destinationpath

    }

    check

    if (check)
    {
    “Success”
    }
    else
    {
    “Fail”
    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.