PowerShell Syntax Essentials

A comprehensive guide to understanding and using PowerShell syntax effectively.

PowerShell is a powerful task automation and configuration management framework from Microsoft, consisting of a command-line shell and an associated scripting language built on the .NET Framework. Understanding its syntax is crucial for leveraging its full potential.

Core Concepts

Cmdlets

PowerShell cmdlets (pronounced "command-lets") are specialized .NET classes designed to perform specific actions. They typically follow a Verb-Noun naming convention.

Example of a cmdlet:

Get-Process

Parameters

Cmdlets accept parameters to modify their behavior. Parameters can be positional (their order matters) or named (identified by a hyphen).

Example of a cmdlet with a named parameter:

Get-Process -Name explorer

Many cmdlets also support common parameters like:

Pipeline

The PowerShell pipeline (represented by the pipe character |) allows you to send the output of one cmdlet as input to another. This is a fundamental feature for building complex commands.

Example of using the pipeline:

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

In this example:

The special variable $_ (or $PSItem) represents the current object in the pipeline.

Scripting Constructs

Variables

Variables in PowerShell start with a dollar sign ($) and are case-insensitive.

$myName = "PowerShell User"
$myNumber = 123
$myArray = @("Apple", "Banana", "Cherry")
$myHash = @{ Key1 = "Value1"; Key2 = "Value2" }

Control Flow

PowerShell supports standard control flow statements like If, ElseIf, Else, Switch, For, ForEach, and While.

If Statement

if ($myNumber -gt 100) {
    Write-Host "Number is greater than 100"
} elseif ($myNumber -eq 100) {
    Write-Host "Number is exactly 100"
} else {
    Write-Host "Number is less than 100"
}

ForEach Loop

foreach ($fruit in $myArray) {
    Write-Host "Current fruit: " + $fruit
}

Functions

You can define your own functions to encapsulate reusable code.

function Say-Hello {
    param (
        [string]$Name = "World"
    )
    Write-Host "Hello, " + $Name + "!"
}

Say-Hello -Name "Alice"
Say-Hello

Comments

Comments are used to explain code. PowerShell supports single-line and block comments.

# This is a single-line comment

<#
This is a
block comment
that spans multiple lines.
#>
Write-Host "Code follows comments."

Operators

PowerShell has a rich set of operators for comparison, arithmetic, logical operations, and more.

Comparison operators often use hyphens, e.g., -eq (equal to), -ne (not equal to), -gt (greater than), -lt (less than), -like (pattern match).

Logical operators include -and, -or, -not (or !).

if ($a -gt $b -and $c -ne 0) {
    Write-Host "Conditions met."
}