DevOps
PowerShell
Variables & Scripting

Variables & Scripting

PowerShell combines a flexible command shell with a robust programming language. This allows you to scale from simple commands to complex automation frameworks.

1. Variables

Variables in PowerShell always start with a $. They can hold strings, numbers, or even complex objects.

# Basic assignment
$projectName = "Project Phoenix"
$retryCount = 3
 
# Storing a command result (as an object)
$services = Get-Service | Where-Object Status -eq "Running"
 
# Accessing properties
echo "There are $($services.Count) running services."

2. Control Flow

PowerShell uses syntax similar to C# and Javascript for logic.

Conditionals (If-Else)

$status = "error"
 
if ($status -eq "success") {
    Write-Host "Operation completed!" -ForegroundColor Green
} else {
    Write-Host "Warning: Operation failed." -ForegroundColor Red
}

Loops (ForEach)

$servers = "Web-01", "Web-02", "DB-01"
 
foreach ($server in $servers) {
    Write-Host "Pinging $server..."
    Test-Connection -ComputerName $server -Count 1
}

3. Scripting Basics

PowerShell scripts are saved with the .ps1 extension.

Execution Policy

To protect against malicious scripts, Windows restricts script execution by default. To run local scripts, you often need to set the policy:

# View current policy
Get-ExecutionPolicy
 
# Set policy to allow local scripts
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

4. Input and Output

  • Read-Host: Get input from the user.
  • Write-Host: Output text to the screen (supports colors).
  • Write-Output: Send data down the pipeline (Standard).
$name = Read-Host "What is your deployment name?"
Write-Host "Initializing deployment for $name..." -ForegroundColor Cyan

[!NOTE] Operators PowerShell uses text-based operators: -eq (equals), -ne (not equal), -gt (greater than), -lt (less than). This prevents confusion with the > and < characters used for redirection.