Those who dabbled in programming would be familiar with the return keyword. The primary use of return, as the name implies, is to return the result and exit a scope. The scope can be a function, script, or script block. Once the return keyword is invoked, PowerShell releases the control to the calling code block.
Table of Contents
PowerShell Return: The Basics
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 will be displayed two times in each iteration, one in green and another 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 }
It seems simple, right? You get the gist. But the PowerShell return keyword has more utility than just terminating the current scope.
PowerShell Function Return
The return keyword uses the following syntax.
return [<expression>]
The [<expression>] can be any PowerShell object and data type, like Boolean, integer, string, etc. Results in PowerShell as sent to the output stream by default, even without invoking the return keyword. So when is return helpful?
Example 1: Return a Calculated Value
Let’s use return in a function called Get-Square using the code below.
Function Get-Square($number) { return [math]::Sqrt($number) "This line will not be displayed" }
As you can see, the PowerShell function return shows the result and exits the function. The “This line will not be displayed” was not sent to the output.
Note. Learn how to comment PowerShell code.
Example 2: Return the Result of a Conditional Match
Another practical PowerShell function return example is when returning a match from a condition. When you run a function that checks whether the value is a match against a collection, the return keyword can return the result and terminate the search in that instance.
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
You can also control the objects to output using the return keyword. For example, the function below (GetServiceAndProcess) 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 store 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
Conclusion
The PowerShell return keyword has two primary purposes: return results and terminate the current scope. Using PowerShell function return keyword allows you to control your code’s output 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”
}
}