PowerShell Call Stack
A call stack is the chain of function calls that led to the current line of code. Get-PSCallStack shows that chain, newest call first.
Get-PSCallStack shows the chain of calls
Three functions call each other in a chain. The innermost function prints the chain.
function Get-Inner { (Get-PSCallStack | Select-Object -ExpandProperty FunctionName) -join " -> " }
function Get-Middle { Get-Inner }
function Get-Outer { Get-Middle }
Get-OuterEach entry also carries its line number
Each entry also carries a line number. The name and the line together show who called and from where.
function Get-Inner { Get-PSCallStack | ForEach-Object { "$($_.FunctionName) line $($_.ScriptLineNumber)" } }
function Get-Middle { Get-Inner }
function Get-Outer { Get-Middle }
Get-OuterA catch block can print the chain behind an error
An error is caught in the innermost function. The stack then shows which calls led to the error.
function Get-Level3 { try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message; (Get-PSCallStack | Select-Object -ExpandProperty FunctionName) -join " -> " } }
function Get-Level2 { Get-Level3 }
function Get-Level1 { Get-Level2 }
Get-Level1Example
function Get-Receipt { try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message; Get-PSCallStack | ForEach-Object { "$($_.FunctionName) line $($_.ScriptLineNumber)" } } }
function Get-Payment { Get-Receipt }
function Get-Order { Get-Payment }
Get-OrderKey points
- Call stack: the chain of function calls that led to the current line of code.
- Use Get-PSCallStack to show the chain while code is running.
- FunctionName: the name of one function in the chain.
- ScriptLineNumber: the line number where one call was made.
- Order: the newest call comes first, and the script itself comes last as <ScriptBlock>.
In this example, Get-Order calls Get-Payment, which calls Get-Receipt. Get-Receipt catches a missing path error, prints the message, then prints each stack entry with its name and line number.
Note
read the stack inside a function, because the chain only exists while the code runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Get-A calls Get-B, and Get-B runs Get-PSCallStack. Which name comes first in the output?