Concept Flow - Return values
Start Function
Execute Statements
Return Value Found?
No→Return Null
Yes
Return Value Sent Back
Function Ends
The function runs its code, then sends back a value if specified, or null if none.
function Get-Sum { param($a, $b) return $a + $b } $result = Get-Sum 3 4 Write-Output $result
| Step | Action | Variables | Return Value | Output |
|---|---|---|---|---|
| 1 | Call Get-Sum with a=3, b=4 | a=3, b=4 | None yet | None |
| 2 | Calculate a + b | a=3, b=4 | 7 | None |
| 3 | Return 7 from function | a=3, b=4 | 7 | None |
| 4 | Assign return value to $result | $result=7 | 7 | None |
| 5 | Write-Output $result | $result=7 | 7 | 7 |
| Variable | Start | After Step 1 | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|---|
| a | undefined | 3 | 3 | undefined | undefined |
| b | undefined | 4 | 4 | undefined | undefined |
| result | undefined | undefined | undefined | 7 | 7 |
PowerShell functions use 'return' to send a value back. Return ends the function immediately. Without return, function returns null. Capture return value by assigning function call to a variable. Use returned value later in script.
return keyword do in a PowerShell function?returnreturn keyword in PowerShell is used inside a function to send a value back to the caller.return.return $value. Other options like send, output, or yield are not valid PowerShell keywords for returning values.function Get-Square {
param($num)
return $num * $num
}
$result = Get-Square -num 4
Write-Output $resultGet-Square takes a number and returns its square by multiplying the number by itself.function Add-Numbers {
param($a, $b)
$sum = $a + $b
Write-Host $sum
}Write-Host to display the sum but does not use return to send the value back to the caller.Write-Host sends output to the pipeline but does not return a value from the function in the expected way for assignment.Pass the test and this pattern moves unknown