In PowerShell, functions can return values in several ways. You can use the return
keyword or simply output the value you want to return, as all output in PowerShell (unless explicitly suppressed) is considered part of the function’s return value.
Defining a Function with Return Value
Here’s the syntax to define and use a function with a return value:
function FunctionName {
# Logic inside the function
return <value>
}
Examples of Returning Values
1. Using return
Keyword
The return
keyword explicitly specifies the value to be returned by the function.
function Add-Numbers {
param ($a, $b)
return $a + $b
}
# Call the function
$result = Add-Numbers -a 5 -b 10
Write-Host "The result is: $result"
Output:
The result is: 15
2. Implicit Output
PowerShell functions automatically return all output unless explicitly suppressed (e.g., using Write-Output
or piping to Out-Null
).
function Multiply-Numbers {
param ($a, $b)
$a * $b # No explicit return
}
# Call the function
$result = Multiply-Numbers -a 4 -b 3
Write-Host "The result is: $result"
Output:
The result is: 12
3. Using Write-Output
The Write-Output
cmdlet is often used to make it explicit that a value is being sent to the output stream.
function Get-Message {
param ($name)
Write-Output "Hello, $name!"
}
# Call the function
$message = Get-Message -name "John"
Write-Host $message
Output:
Hello, John!
Multiple Return Values
PowerShell functions can return multiple values by outputting multiple objects.
function Get-Numbers {
1
2
3
}
# Call the function
$result = Get-Numbers
Write-Host "The numbers are: $result"
Output:
The numbers are: 1 2 3
If you want the return values as an array:
$result = @(Get-Numbers)
Write-Host "The numbers are: $($result -join ', ')"
Output:
The numbers are: 1, 2, 3
Suppressing Output
If you don’t want certain values to be returned, suppress them using Out-Null
or enclosing them in parentheses.
function No-Output {
"This won't be returned" | Out-Null
return "This is the return value"
}
# Call the function
$result = No-Output
Write-Host $result
Output:
This is the return value
Conclusion
In PowerShell:
- Use
return
for explicit returns. - Output is implicitly returned unless suppressed.
- Multiple values can be returned as a collection.
- Use
Out-Null
to suppress unwanted output.
This flexibility makes PowerShell functions versatile and efficient for a variety of use cases.