Those who dabbled in programming would be familiar with the return keyword. The primary use of return in PowerShell is to return the result of a function and/or exit the current scope. The scope can be a function, script, or script block. After the Return statement is invoked, PowerShell exits a function and returns control to the calling code. In this article, we’ll look at examples of how to use the Return statement in PowerShell scripts.
Table of Contents
Return Behavior in PowerShell
The Return statement can be used in PowerShell to exit the current scope. To illustrate, the code below prints the string “The number is %n”, where %n is 1 to 5.
for ($i = 1; $i -le 5; $i++) { "The number is $i" }
But when you insert the return keyword after the result, the whole iteration is terminated after the first result.
for ($i = 1; $i -le 5; $i++) { "The number is $i" return }
As you can see below, the for loop is terminated after the first result is displayed because of the return keyword that followed.
Let’s look at another example. The code below prints the string “The number is %n” where %n is the numbers 1 to 5. The result is displayed twice in each iteration, once in green and once in magenta.
1..5 | ForEach-Object { Write-Host "The number is $_" -ForegroundColor Green Write-Host "The number is $_" -ForegroundColor Magenta }
But when you insert the Return keyword, it terminates the loop and returns the control to the calling code.
1..5 | ForEach-Object { Write-Host "The number is $_" -ForegroundColor Green return Write-Host "The number is $_" -ForegroundColor Magenta }
When you use the Return statement in pipeline cmdlets (such as ForEach-Object, Where-Object, etc.), the return doesn’t exit the loop processing, but only moves to the next item in the pipeline:
Get-ADUser -filter *| foreach-object { if (!$_.enabled) { return $_.UserPrincipalName} }
Use the Break statement instead of Return to exit the loop.
Return Value from Function in PowerShell Return
The most common use of the Returns operator is to return the results of a PowerShell function.
The return keyword syntax:
return [<expression>]
The [<expression>] can be any PowerShell object and data type, like Boolean, integer, string, or even a statement (such as return (24 + $abc)). In PowerShell, you can return values from a function even if you do not use the Return keyword. PowerShell functions don’t return values by default, and all output from within the function is shown as output in the console, which is very confusing.
So, when is return helpful? The Return keyword is used to return only specific value(s) from a function and exit the function scope.
Example 1: Return a Calculated Value from a PowerShell Function
Let’s use return in a function called Get-Square:
Function Get-Square($number) { return [math]::Sqrt($number) "This line will not be displayed" }
In this example, the Return statement in fiction shows the result and exits the scope. The “This line will not be displayed” was not sent to the output.
Example 2: Return the Result of a Conditional Match
Returning a match from a condition is another practical example of a PowerShell function return. When you run a function that checks whether the value is a match against a collection, the return keyword can return the result and stop the search.
First, let’s try a function without the return keyword.
Function Find-Number { param ( [int[]]$numCollection, [int]$numToFind ) for ($i = 0 ; $i -lt $numCollection.Count; $i++) { if ($numCollection[$i] -eq $numToFind) { "Found the number $numToFind at position $i" } } }
This Find-Number function takes two parameters:
- $numCollection — an array of numbers to use as lookup values.
- $numToFind — the single number to find in the $numCollection array.
Now let’s invoke the function by running the command below.
Find-Number -numCollection 1,5,3,6,7,6 -numToFind 6
The command will look for the number 6 with the array of 1,5,3,6,7,6. According to the result below, the function found two instances of the number 6 in the collection, which is correct.
But what if we want the function to terminate when it finds the first instance? Then we can use the return keyword instead. Let’s add the return keyword at the beginning of line 8.
This time, the PowerShell function returns the first instance and terminates.
Example 3: Return Multiple Objects from a Function
You can also control the objects to output using the return keyword. For example, the function below (returns two objects: Services (System.Service.ServiceController) and Processes (System.Diagnostics.Process).
Function GetServiceAndProcess { return ` $( Get-Service -ErrorAction SilentlyContinue | Select-Object -First 5 ), $( Get-Process -ErrorAction SilentlyContinue | Select-Object -First 5 ) } Invoke the PowerShell function and save the results in the $result variable. $result = GetServiceAndProcess ($result[0] | Get-Member)[0].TypeName ($result[1] | Get-Member)[0].TypeName
Or you could store the PowerShell function return result to separate variables like so:
$service, $process = GetServiceAndProcess $service $process
The PowerShell Return keyword has two primary purposes: returning results and exiting the current scope. By using the Return keyword in PowerShell functions, you can control the output of your code and when and where to exit.
1 comment
Hi please help me with this code i am always getting a failed results.
$files = Get-Content C:temptestinfo.txt
foreach($file in $files)
{
$sourcePath = “C:temptestsource” + $file
$destinationpath = “C:temptestdestination”
function check()
{
Copy-Item $sourcePath $destinationpath
}
check
if (check)
{
“Success”
}
else
{
“Fail”
}
}