Skip to content

Functions

image.png

image.png

image.png


  • Defined inside the param() block.
  • You specify the parameter name when calling the function.
  • Can have default values.
Terminal window
function Show-ParamExample {
param(
$Name = "Example"
)
"Name is $Name"
}
Terminal window
Show-ParamExample
# Output: Name is Example
Show-ParamExample -Name "Pavan"
# Output: Name is Pavan

✔ If no value is given → default is used.

✔ If value is given → it overrides default.


  • No need to specify parameter name.
  • PowerShell assigns values based on order.
  • Values go into $args array if not defined in param().
Terminal window
function Show-Positional {
"First value: $($args[0])"
}
Show-Positional Hello
# Output: First value: Hello

✔ First value after function name → $args[0]

✔ Second value → $args[1]


Better Positional Example (With Param Block)

Section titled “Better Positional Example (With Param Block)”
Terminal window
function Add-Numbers {
param(
$A,
$B
)
$A + $B
}

Usage:

Terminal window
Add-Numbers 5 10
# Output: 15

Here:

  • 5 → $A
  • 10 → $B

image.png

  • Do NOT require a value.
  • Either present (True) or not present (False).
  • Used for flags like Verbose.
Terminal window
function Test-Switch {
param(
[switch]$Upper
)
if ($Upper) {
"HELLO"
}
else {
"hello"
}
}
Terminal window
Test-Switch
# Output: hello
Test-Switch -Upper
# Output: HELLO

✔ If -Upper is used → $Upper = True

✔ If not used → $Upper = False


Parameter TypeNeeds Name?Needs Value?Example
NamedYesYes-Name "Pavan"
PositionalNoYes5 10
SwitchYesNo-Upper

✅ PowerShell Functions & Pipeline – Simple Notes

Section titled “✅ PowerShell Functions & Pipeline – Simple Notes”
  • Any function can accept objects from the pipeline.
  • Control pipeline processing using begin, process, end blocks.

BlockWhen it runsHow often
beginBefore any objects come from pipelineOnce
processFor each object from pipelineOnce per object
endAfter all objects are processedOnce
  • Objects from pipeline → assigned to $_ automatically in process block.
  • If begin/process/end are not used → all code acts like end.

Terminal window
function Show-Items {
begin {
"Starting function..."
}
process {
"Processing item: $_"
}
end {
"All items processed."
}
}
Terminal window
1,2,3 | Show-Items

Output:

Starting function...
Processing item: 1
Processing item: 2
Processing item: 3
All items processed.

  • $_ → represents current object in process block.
  • begin → initialize things (e.g., counters, variables).
  • process → main work on each object.
  • end → finalize (e.g., display totals, cleanup).

Terminal window
function Show-ItemsSimple {
"Item: $_"
}

Usage:

Terminal window
1,2,3 | Show-ItemsSimple

Output:

Item: 1
Item: 2
Item: 3
  • Here, all code is treated like end → still works, but less control.

image.png


image.png