PowerShell Command Syntax

Understanding the Structure

PowerShell commands, often referred to as cmdlets, follow a Verb-Noun naming convention. This makes them intuitive and predictable. For example, Get-Process retrieves information about running processes.

The general syntax for a command is:

Verb-Noun [-ParameterName ] [-SwitchParameter]
                    

Key Components

  • Verb: An action, such as Get, Set, New, Remove, Invoke, etc.
  • Noun: The object the verb acts upon, such as Process, Service, File, Computer, etc.

Parameters

Cmdlets can accept parameters to refine their operation. Parameters can be positional or named.

Named Parameters: Specified with a hyphen (-) followed by the parameter name and its value.

Get-Service -Name 'BITS'

Here, -Name is a named parameter, and 'BITS' is its value.

Positional Parameters: If a parameter is positional, you can omit the parameter name if it's the first parameter, or if the order of parameters is correct. PowerShell uses the order of arguments to determine which parameter they apply to.

Get-Service BITS

In this case, 'BITS' is treated as the value for the first positional parameter of GetService, which is typically the name of the service.

Switch Parameters: These are parameters that don't take a value. Their presence indicates that a certain option should be enabled. They are often boolean.

Get-Process -IncludeUserName

The -IncludeUserName switch tells Get-Process to display the username associated with each process.

Parameter Sets: Some cmdlets have different sets of parameters that can be used together. PowerShell helps manage these automatically. You can view available parameter sets using Get-Help <CmdletName> -Parameter *.

Pipes (|)

The pipe character (|) is fundamental to PowerShell. It passes the output of one command as input to another command.

Get-Process | Where-Object {$_.CPU -gt 100} | Sort-Object CPU -Descending

This example first gets all processes, then filters them to show only those using more than 100 CPU seconds, and finally sorts the results by CPU usage in descending order.

Common Cmdlets for Syntax Exploration

  • Get-Command: Finds cmdlets and other commands.
  • Get-Help: Displays detailed information about cmdlets and their parameters. Use Get-Help <CmdletName> -Full for comprehensive details.
  • Get-Member: Shows properties and methods of PowerShell objects.

Example: To understand the syntax and parameters of Get-Service, you can run:

Get-Help Get-Service -Examples