0
0
PowerShellscripting~10 mins

Return values in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Return values
Start Function
Execute Statements
Return Value Found?
NoReturn Null
Yes
Return Value Sent Back
Function Ends
The function runs its code, then sends back a value if specified, or null if none.
Execution Sample
PowerShell
function Get-Sum {
  param($a, $b)
  return $a + $b
}

$result = Get-Sum 3 4
Write-Output $result
This function adds two numbers and returns the sum, which is then printed.
Execution Table
StepActionVariablesReturn ValueOutput
1Call Get-Sum with a=3, b=4a=3, b=4None yetNone
2Calculate a + ba=3, b=47None
3Return 7 from functiona=3, b=47None
4Assign return value to $result$result=77None
5Write-Output $result$result=777
💡 Function ends after return statement sends value 7 back.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
aundefined33undefinedundefined
bundefined44undefinedundefined
resultundefinedundefinedundefined77
Key Moments - 3 Insights
Why does the function stop running after the return statement?
Because the return statement immediately sends the value back and exits the function, as shown in execution_table step 3.
What happens if there is no return statement in the function?
The function returns null or nothing by default, so no value is sent back, unlike step 3 where return 7 is explicit.
How is the returned value captured outside the function?
The returned value is assigned to a variable like $result in step 4, so it can be used later.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the return value at step 3?
A3
BNone yet
C7
DUndefined
💡 Hint
Check the 'Return Value' column at step 3 in the execution_table.
At which step is the returned value assigned to $result?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Variables' column to see when $result gets a value.
If the return statement was removed, what would be the output at step 5?
ANull or empty
B7
CError
D3
💡 Hint
Without return, the function sends back nothing, so $result would be empty.
Concept Snapshot
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.
Full Transcript
In PowerShell, a function can send a value back using the return statement. When the function runs, it executes its code. Once it hits return, it immediately stops and sends the specified value back to where it was called. If no return is used, the function returns nothing (null). Outside the function, you can save this returned value in a variable to use later. For example, a function adding two numbers returns their sum, which you can print or use elsewhere.