Defining a Function
function Get-Factorial {
param([int]$n)
if ($n -le 1) { return 1 }
return $n * (Get-Factorial -n ($n - 1))
}
Get-Factorial -n 5 # 120
Key parts:
- function Name { } — declaration (Verb-Noun naming convention, e.g. Get-, Set-)
- param(...) — parameter block with optional type hints like [int], [string]
- return — optional; PowerShell outputs anything not captured, but return makes intent explicit
Recursive Pattern (File Collector)
function Get-AllFiles {
param([string]$Root)
$files = @()
foreach ($entry in Get-ChildItem -Path $Root) {
if ($entry.PSIsContainer) {
$files += Get-AllFiles -Root $entry.FullName # recursive case
} else {
$files += $entry.FullName # base case
}
}
return $files
}
Base case / recursive case logic is identical to Python's — only syntax differs:
- $entry.PSIsContainer detects directories (true for folders)
- Get-ChildItem lists entries (like os.listdir)
- Parameters are passed as named args: -Root $path
Practical Tips
$files += ...is convenient but slow on huge trees; prefer building output through the pipeline (Get-ChildItem -Recursealso exists for the simple case).- Recursion depth in PowerShell is limited — for very deep folder trees, an iterative loop with an explicit stack may be safer.
Compare with Python Function Basics and Recursion — same concepts, different syntax.