Core Skills Level: Intermediate Chapter 8: Build Your Own Commands
Advanced Functions
An advanced function looks and feels like a built in cmdlet, with validation, common parameters, pipeline support, and safety checks.
Lesson 2 of 2 in Chapter 8: Build Your Own Commands. Previous step in this path: Functions. 3 learning objectives, 6 examples, and a knowledge check.
Start: what you will learn
An advanced function looks and feels like a built in cmdlet, with validation, common parameters, pipeline support, and safety checks.
Learning objectives
- Describe what makes a function advanced
- Use CmdletBinding and Parameter attributes
- Add validation, pipeline input, and ShouldProcess safety
Concept in simple words
What it is: An advanced function is a function that behaves like a built in cmdlet. You make a function advanced by adding the [CmdletBinding()] attribute, or a [Parameter()] attribute, or both, just before the param block. From the outside, the change feels small, because you still call it by name with named parameters. From the inside, PowerShell now gives the function extra powers, such as common parameters, input validation, and pipeline support.
What problem it solves: A simple function is perfect for your own quick helper, but it trusts the caller completely. It accepts an empty name, a wild number, or a missing value, and only fails later, deep inside the body, where the real cause is hard to find. An advanced function moves those checks to the front door. Bad input is stopped before the body runs, with a clear error, and dangerous work can be previewed before it happens. That front door check is what makes a shared tool safe to hand to someone else.
Why it works
Why it exists: Built in cmdlets feel consistent because they share the same habits. They ask for required values, they accept pipeline input, they show extra detail with -Verbose, and they preview changes with -WhatIf. Advanced functions let your own commands join that same family, so people who already know PowerShell do not need to learn a new set of habits for your tool. Consistency is not decoration. It is what lets a stranger use your function correctly on the first try.
Think of it like this
Think of it like this: A simple function is like a home recipe card, written for yourself, with steps you already understand. An advanced function is like a recipe printed for a whole kitchen team, with the ingredients checked at the door, the quantities in clear limits, a preview step before the oven is turned on, and notes that appear only when the head cook asks for detail. The dish is the same, but the printed version protects every cook who uses it.
Behind the command, what CmdletBinding adds: When you add [CmdletBinding()], PowerShell adds common parameters to your function, such as -Verbose, -Debug, -ErrorAction, and -WarningAction. You do not write those parameters yourself. PowerShell provides them, and it handles them in the same way for every advanced function. That is why -Verbose works on your function without you writing any verbose handling code, as long as you also write messages with Write-Verbose.
Behind the command, Write-Verbose in depth: Write-Verbose writes a message to the verbose stream, which is a separate channel from the normal output. By default, that channel stays quiet, so a normal call shows only the real result. Add -Verbose to the call, and the verbose messages appear, which helps you trace what the function did, step by step, without polluting the result. Never put tracing text in the normal output, because the caller may store that output and treat your tracing text as real data.
How it works, step by step
How it works, step by step, step 1, add the attribute: Write [CmdletBinding()] on the line just before the param block, inside the function braces. The square brackets mark it as an attribute, which is extra instruction to PowerShell about how the function should behave. One small line changes the whole character of the function, from a simple helper to a cmdlet style tool.
How it works, step by step, step 2, mark each parameter: Above each parameter, add a [Parameter()] attribute when you need extra control, such as Mandatory, or ValueFromPipeline. Inside the round brackets, you write settings as name and value pairs, for example [Parameter(Mandatory = $true)]. Then, on the next line, you still write the type and the variable name, such as [string]$Name. The attribute and the type work together. The attribute controls how the parameter is used, and the type controls what kind of value it accepts.
How it works, step by step, step 3, add validation: Above a parameter, you can add a validation attribute, such as [ValidateNotNullOrEmpty()], [ValidateSet("Formal", "Friendly")], [ValidateRange(0, 100)], or [ValidateLength(1, 50)]. PowerShell checks these rules before the body runs. If a value breaks a rule, the call stops with an error, and the body never starts. That early stop keeps bad data out of your logic, and it gives the caller a clear message about which rule was broken.
Mandatory in depth: A mandatory parameter must be given a value. In an interactive session, if you forget it, PowerShell pauses and asks you to type it. In a session that cannot ask, the call fails instead. That behaviour is helpful, because a missing name or path is caught at the start, not halfway through a job. Do not give a mandatory parameter a default value and expect the default to be used, because PowerShell will still ask for a value when the caller gives none.
Validation in depth, one rule at a time: [ValidateNotNullOrEmpty()] rejects an empty value, a null value, and an empty list. [ValidateSet()] allows only the listed words, which is perfect for a choice like a style or a mode, because a typo becomes a clear error instead of a silent wrong branch. [ValidateRange()] allows only numbers inside the range, so a score of 150 cannot sneak into a 0 to 100 scale. [ValidateLength()] limits how long a text value may be. Choose the narrowest rule that is still honest, because a rule that is too strict will reject good input too.
Pipeline in depth, why process matters: For pipeline input, you need three named blocks to understand: begin, process, and end. The begin block runs once before the first piped item, and it is the place for one time setup. The process block runs once for every piped item, and it is where you handle the current item, which PowerShell gives you as $_. The end block runs once after the last item, and it is the place for a summary or cleanup. If you use any named block, put all your code in named blocks, because mixing plain code with named blocks causes an error.
Pipeline in depth, two ways to accept piped input: ValueFromPipeline means the whole piped object goes into that parameter, value by value. ValueFromPipelineByPropertyName means PowerShell looks at the piped object for a property with the same name as the parameter, and uses that property value. The second form is powerful for real objects, because a list of objects that already carry a Name property can flow straight into a -Name parameter without a loop written by the caller. In both cases, the process block is what makes the function act on each item in turn.
ShouldProcess in depth, the safety preview: Some functions change things, such as deleting a file, and a mistake there cannot be undone with an apology. For those functions, add SupportsShouldProcess to CmdletBinding, like this: [CmdletBinding(SupportsShouldProcess = $true)]. Then, wrap the changing step in a test: if ($PSCmdlet.ShouldProcess($Path, "Remove file")) { Remove-Item -Path $Path }. The variable $PSCmdlet is the built in handle PowerShell gives an advanced function, and ShouldProcess asks the safety question for you.
ShouldProcess in depth, WhatIf and Confirm: Once SupportsShouldProcess is set, callers gain -WhatIf and -Confirm without you writing those parameters. The -WhatIf call shows what would happen, but makes no change, which is the safe way to test a changing function. The -Confirm call asks the caller to approve before the change happens. Warning: test a changing function with -WhatIf first, and only use a test file you can afford to lose, because a real call without -WhatIf will actually carry out the change.
ShouldProcess in depth, the common trap: Adding SupportsShouldProcess alone does not protect anything. The protection only works if the changing code sits inside the if ($PSCmdlet.ShouldProcess(...)) test. If you add the attribute but call Remove-Item outside that test, then -WhatIf will not stop the deletion, and the safety label will be a lie. Always check that the risky line is inside the test, and test it with -WhatIf on a throwaway file before you trust it.
OutputType in depth: The [OutputType()] attribute, written above the param block, documents what kind of result the function sends out, for example [OutputType([string])] for text results. Think of it as a label on the parcel, not a lock on the box. It helps readers and tools understand what to expect, but the real guarantee still comes from writing a clean body that returns only the intended result.
Parameter sets in plain words: Sometimes one function has two valid shapes, such as finding something by name or by number, but not both at once. Parameter sets let you describe those shapes, so PowerShell can require the right mandatory values for each shape and reject a mixed call that makes no sense. You do not need parameter sets for most beginner functions, but it is useful to know the idea exists, because it explains why some built in commands accept one group of parameters and refuse another group.
Help and readability in depth: A shared function deserves a short comment above it that says what it does, what each parameter means, and one example call. That comment is the first help a reader sees, and it costs almost nothing to write. Also, keep the Verb-Noun name honest: Get for reading, New for creating, Set for changing, Remove for deleting, and Test for checking. A name that promises Get but actually deletes will surprise and harm its users, no matter how good the code inside is.
Let us walk through an example, CmdletBinding with Verbose: In the first example, [CmdletBinding()] sits before param, and [Parameter(Mandatory = $true)] plus [ValidateNotNullOrEmpty()] sit above $Name. The body writes a verbose message with Write-Verbose, then returns the greeting. The call adds -Verbose, so you see both the tracing line and the greeting. Run the same call without -Verbose, and the tracing line disappears while the greeting stays, which proves the verbose message never polluted the real result.
Let us walk through an example, ValidateSet: In the ValidateSet example, $Style may only be "Formal" or "Friendly". The body checks the style and returns the matching greeting. The call with -Style "Friendly" returns the friendly greeting. If you change the call to -Style "Casual", PowerShell stops before the body runs, because "Casual" is not in the allowed set. Look for that early error as the sign that validation is working, not as a failure of the function.
Let us walk through an example, ValidateRange: In the ValidateRange example, $Score must sit between 0 and 100. The body returns "Pass" for 50 or more, and "Review" for less than 50. The call with -Score 82 returns "Pass". Change the call to -Score 150, and PowerShell stops with a validation error before any Pass or Review logic runs. That is the whole point: the body never has to defend itself against an impossible score, because the front door already refused it.
Let us walk through an example, pipeline with process: In the pipeline example, [Parameter(ValueFromPipeline = $true)] tells PowerShell that piped values go into $Name, and the process block turns each $Name into capital letters with $Name.ToUpper(). The call "izaz", "sam" | Get-UpperName sends two items, one at a time, so you see two lines, IZAZ and then SAM. If you put that same line in the end block instead of process, it would not run once per item in the way you expect, which is why process matters for pipeline functions.
Let us walk through an example, ShouldProcess with WhatIf: In the ShouldProcess example, the function first asks $PSCmdlet.ShouldProcess($Path, "Remove file") before it touches anything. The call adds -WhatIf, so PowerShell shows a "What if" preview line and skips the real deletion. Look for that preview line in the output, and notice that no file was removed. Warning: do not run this example without -WhatIf on a file you need, and test it only on a throwaway test file, because the same function without -WhatIf would actually delete the file at that path.
Let us walk through an example, pipeline by property name: In the last example, the piped object is a small custom object with a Name property, written as [pscustomobject]@{ Name = "Izaz" }. The parameter uses ValueFromPipelineByPropertyName, so PowerShell matches the Name property to the $Name parameter by name, without the caller writing a loop. The process block returns "Hello, Izaz". If you change the property value to "Sam", the greeting changes to "Hello, Sam", because the property, not a fixed value, drives the result.
Common mistakes and edge cases in the body: A frequent mistake is writing -Verbose in a simple function and wondering why nothing extra appears, because Write-Verbose only shows its message when the function is advanced and the caller adds -Verbose. Another mistake is adding a validation rule that is too strict, such as a length limit that rejects a perfectly good long name, which turns a safety feature into a barrier. A third mistake is forgetting that validation runs before the body, so a validation error means the body never ran, and any setup code in begin never had a chance to matter for that call.
When to use it
When to use it, and when not to: Use an advanced function when other people will use your tool, when bad input could cause confusion or harm, when the function changes something, or when pipeline input would make it much easier to use. Stay with a simple function for a quick personal helper that only you will run, that changes nothing, and that takes one or two simple inputs. Starting simple and upgrading to advanced later is a good path. Add CmdletBinding and validation when the function grows up and starts serving others, not before you need them.
Worked examples
Read each example in order. Each one explains its parts, then shows what to look for in the output.
Syntax
[CmdletBinding()] function <Name> { param([Parameter(Mandatory)][ValidateSet(<Values>)]<Type>$<Parameter>) begin {} process {} end {} }Example 1
[CmdletBinding()] makes the function advanced and adds -Verbose. [Parameter(Mandatory = $true)] requires a value, and [ValidateNotNullOrEmpty()] rejects an empty value. Write-Verbose shows only with -Verbose, so the real result stays clean.
function Get-AdvancedGreeting {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Name
)
Write-Verbose "Building a greeting for $Name."
"Hello, $Name"
}
Get-AdvancedGreeting -Name "Izaz" -VerboseIllustrative output: VERBOSE: Building a greeting for Izaz. Hello, Izaz
Example 2
[ValidateSet("Formal", "Friendly")] allows only those two words for -Style. "Friendly" takes the else branch and returns "Hi, Izaz". Change -Style to "Casual" and PowerShell stops with a validation error before the body runs.
function Get-GreetingStyle {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet("Formal", "Friendly")]
[string]$Style,
[string]$Name = "friend"
)
if ($Style -eq "Formal") { "Good day, $Name" } else { "Hi, $Name" }
}
Get-GreetingStyle -Style "Friendly" -Name "Izaz"Illustrative output: Hi, Izaz
Example 3
[ValidateRange(0, 100)] allows only scores from 0 to 100. The score 82 is inside the range, so the body runs and returns "Pass". Change -Score to 150 and PowerShell stops with a validation error before the body runs.
function Get-ScoreLabel {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateRange(0, 100)]
[int]$Score
)
if ($Score -ge 50) { "Pass" } else { "Review" }
}
Get-ScoreLabel -Score 82Illustrative output: Pass
Example 4
ValueFromPipeline sends each piped value into $Name, and the process block runs once per value. The first item becomes IZAZ and the second becomes SAM. Put the work in process, not in the end block, so it runs once per piped item.
function Get-UpperName {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true)]
[string]$Name
)
process { $Name.ToUpper() }
}
"izaz", "sam" | Get-UpperNameIllustrative output: IZAZ SAM
Example 5
Warning: this function can delete a file. The call uses -WhatIf, so PowerShell shows a preview and makes no change. Only test this pattern on a throwaway test file you can afford to lose, and always test with -WhatIf before a real call.
function Remove-TestFile {
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string]$Path
)
process {
if ($PSCmdlet.ShouldProcess($Path, "Remove file")) {
Remove-Item -Path $Path
}
}
}
Remove-TestFile -Path "C:\Temp\test.txt" -WhatIfIllustrative output: What if: Performing the operation "Remove file" on Target "C:\Temp\test.txt".
Example 6
ValueFromPipelineByPropertyName matches the piped object Name property to the $Name parameter by name. The caller writes no loop. Change the property value to "Sam" and the greeting becomes "Hello, Sam".
function Get-PersonGreeting {
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]$Name
)
process { "Hello, $Name" }
}
[pscustomobject]@{ Name = "Izaz" } | Get-PersonGreetingIllustrative output: Hello, Izaz
Nothing on this page executes PowerShell code. The outputs above are illustrative only.
Common mistakes and troubleshooting
Read these before you try the examples, so you can spot the same problems in your own work.
- Adding [CmdletBinding()] but expecting -Verbose output without using Write-Verbose, so nothing extra appears, because -Verbose only reveals messages written to the verbose stream.
- Adding SupportsShouldProcess but placing the changing command outside the if ($PSCmdlet.ShouldProcess(...)) test, so -WhatIf does not stop the change.
- Putting pipeline work in the end block instead of the process block, so it does not run once per piped item in the way the caller expects.
- Writing validation that is too strict, such as a length or range limit that rejects good input, which turns a safety feature into a barrier for callers.
- Giving a mandatory parameter a default value and expecting the default to be used, when PowerShell still asks for a value if the caller gives none.
- Forgetting that validation runs before the body, then wondering why setup code in begin never ran for a call that failed validation.
- Declaring -WhatIf or -Confirm by hand as normal parameters instead of using SupportsShouldProcess, which gives a weaker, inconsistent version of the built in safety behaviour.
- Using a Verb-Noun name that promises a safe action, such as Get, for a function that actually changes or deletes something, which surprises and misleads callers.
- Making every small personal helper advanced from the start, which adds noise and rules before the function has earned them, so start simple and upgrade when the function is shared or changes something.
Knowledge check
Knowledge check
What makes a function an advanced function?
Pick one answer. Feedback appears right away, and you can try again.
Remember this and next step
Remember this: An advanced function is a simple function with a front door. CmdletBinding gives it the common parameters, Parameter marks what is required or piped, validation stops bad input before the body runs, process handles each piped item in turn, and ShouldProcess gives dangerous work a preview and a confirmation step. Build the simple version first, make it correct, then add these guards one at a time, testing each one, so your tool stays clear, safe, and easy for others to trust.
Next step: Sequence and selection: if, elseif, else