How to Use Cmdlet in PowerShell: Syntax and Examples
In PowerShell, a
cmdlet is a lightweight command used to perform a specific task. You use a cmdlet by typing its name followed by optional parameters, like Get-Process to list running processes. Cmdlets are easy to combine and automate tasks in scripts.Syntax
A PowerShell cmdlet typically follows this pattern:
Verb-Noun: The cmdlet name, whereVerbdescribes the action andNoundescribes the resource.-ParameterName ParameterValue: Optional parameters to customize the cmdlet's behavior.
Example: Get-Process -Name notepad gets the process named Notepad.
powershell
Verb-Noun [-ParameterName ParameterValue] ...
Example
This example shows how to use the Get-Process cmdlet to list all running processes and then filter to show only Notepad processes.
powershell
Get-Process Get-Process -Name notepad
Output
Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName
------- ------ ----- ----- ------ -- -----------
123 10 15000 20000 0.03 1234 notepad
110 8 14000 18000 0.01 5678 notepad
Common Pitfalls
Common mistakes when using cmdlets include:
- Typing the cmdlet name incorrectly (PowerShell cmdlets are case-insensitive but spelling matters).
- Forgetting the dash
-before parameter names. - Using parameters that do not exist for the cmdlet.
- Not understanding that some cmdlets require administrative privileges.
Always check cmdlet help with Get-Help Cmdlet-Name to avoid errors.
powershell
Get-Process Name notepad # Wrong: missing dash before parameter Get-Process -Name notepad # Correct
Output
Get-Process : A positional parameter cannot be found that accepts argument 'Name'.
At line:1 char:1
+ Get-Process Name notepad
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand
Quick Reference
Here are some useful tips for using cmdlets:
- Use
Get-Help Cmdlet-Nameto learn about any cmdlet. - Use
Get-Commandto find cmdlets available on your system. - Combine cmdlets with the pipeline
|to pass output from one cmdlet to another. - Use tab completion to quickly fill cmdlet names and parameters.
Key Takeaways
Cmdlets follow a Verb-Noun naming pattern and perform specific tasks.
Use parameters with a dash before their name to customize cmdlet behavior.
Check cmdlet details with Get-Help to avoid common mistakes.
Combine cmdlets using the pipeline to automate complex tasks.
Use tab completion and Get-Command to explore available cmdlets.