#PowerShell Scripting

PowerShell is Microsoft's task automation framework with a powerful scripting language.

#📋 Table of Contents


#PowerShell Basics

#Running Commands

powershell
1# Get help
2Get-Help Get-Process
3Get-Help Get-Process -Examples
4
5# Find commands
6Get-Command *service*
7Get-Command -Verb Get
8
9# Cmdlet naming: Verb-Noun
10Get-Process
11Stop-Process
12New-Item
13Remove-Item

#Common Aliases

powershell
1# PowerShell aliases
2ls      # Get-ChildItem
3cd      # Set-Location
4pwd     # Get-Location
5cp      # Copy-Item
6mv      # Move-Item
7rm      # Remove-Item
8cat     # Get-Content
9echo    # Write-Output

#Variables and Types

powershell
1# Variables
2$name = "DevOps"
3$count = 42
4$isEnabled = $true
5
6# Arrays
7$servers = @("web-01", "web-02", "web-03")
8$servers[0]        # First element
9$servers.Count     # Length
10
11# Hash tables
12$config = @{
13    Name = "web-server"
14    Port = 8080
15    Enabled = $true
16}
17$config.Name
18$config["Port"]
19
20# Automatic variables
21$PSVersionTable    # PowerShell version
22$env:USERNAME      # Environment variables
23$env:COMPUTERNAME

#Control Flow

#If Statements

powershell
1if ($status -eq "healthy") {
2    Write-Host "All good"
3}
4elseif ($status -eq "warning") {
5    Write-Host "Check logs"
6}
7else {
8    Write-Host "Critical!"
9}
10
11# Comparison operators
12-eq    # Equal
13-ne    # Not equal
14-lt    # Less than
15-gt    # Greater than
16-le    # Less or equal
17-ge    # Greater or equal
18-like  # Wildcard match
19-match # Regex match

#Loops

powershell
1# ForEach
2foreach ($server in $servers) {
3    Write-Host "Processing $server"
4}
5
6# For
7for ($i = 0; $i -lt 10; $i++) {
8    Write-Host "Index: $i"
9}
10
11# While
12while ($count -lt 5) {
13    Write-Host $count
14    $count++
15}
16
17# Pipeline ForEach
18$servers | ForEach-Object {
19    Write-Host "Server: $_"
20}

#Switch

powershell
1switch ($action) {
2    "start"   { Write-Host "Starting..." }
3    "stop"    { Write-Host "Stopping..." }
4    "restart" { Write-Host "Restarting..." }
5    default   { Write-Host "Unknown action" }
6}

#Functions

powershell
1# Simple function
2function Greet {
3    param([string]$Name)
4    Write-Host "Hello, $Name!"
5}
6Greet -Name "DevOps"
7
8# Advanced function
9function Test-ServerHealth {
10    [CmdletBinding()]
11    param(
12        [Parameter(Mandatory=$true)]
13        [string]$ComputerName,
14        
15        [int]$Port = 80,
16        
17        [int]$Timeout = 5000
18    )
19    
20    try {
21        $tcp = New-Object System.Net.Sockets.TcpClient
22        $connect = $tcp.BeginConnect($ComputerName, $Port, $null, $null)
23        $wait = $connect.AsyncWaitHandle.WaitOne($Timeout, $false)
24        
25        if ($wait) {
26            $tcp.EndConnect($connect)
27            $tcp.Close()
28            return $true
29        }
30        return $false
31    }
32    catch {
33        return $false
34    }
35}
36
37# Usage
38if (Test-ServerHealth -ComputerName "google.com" -Port 443) {
39    Write-Host "Server is healthy"
40}

#Working with Objects

powershell
1# Get objects
2$processes = Get-Process
3
4# Select properties
5Get-Process | Select-Object Name, CPU, WorkingSet
6
7# Filter
8Get-Process | Where-Object { $_.CPU -gt 10 }
9
10# Sort
11Get-Process | Sort-Object CPU -Descending
12
13# Format output
14Get-Process | Format-Table Name, CPU, WorkingSet -AutoSize
15Get-Process | Format-List *
16
17# Export
18Get-Process | Export-Csv -Path "processes.csv"
19Get-Process | ConvertTo-Json | Out-File "processes.json"

#File Operations

powershell
1# Read file
2$content = Get-Content "file.txt"
3$content = Get-Content "file.txt" -Raw  # As single string
4
5# Write file
6"Hello" | Out-File "file.txt"
7Set-Content -Path "file.txt" -Value "Hello"
8Add-Content -Path "file.txt" -Value "New line"
9
10# Check if exists
11Test-Path "file.txt"
12
13# Create directory
14New-Item -ItemType Directory -Path "newdir"
15
16# Copy/Move/Delete
17Copy-Item "source.txt" "dest.txt"
18Move-Item "old.txt" "new.txt"
19Remove-Item "file.txt" -Force

#Remote Management

powershell
1# Enable remoting
2Enable-PSRemoting -Force
3
4# Remote command
5Invoke-Command -ComputerName Server01 -ScriptBlock {
6    Get-Service
7}
8
9# Remote session
10$session = New-PSSession -ComputerName Server01
11Enter-PSSession $session
12Exit-PSSession
13Remove-PSSession $session
14
15# Multiple computers
16$servers = @("Server01", "Server02")
17Invoke-Command -ComputerName $servers -ScriptBlock {
18    Restart-Service nginx
19}

#Script Template

powershell
1#Requires -Version 5.1
2
3<#
4.SYNOPSIS
5    Deploy script for applications
6.DESCRIPTION
7    Deploys the application to specified environment
8.PARAMETER Environment
9    Target environment (staging/production)
10.EXAMPLE
11    .\Deploy.ps1 -Environment staging
12#>
13
14[CmdletBinding()]
15param(
16    [Parameter(Mandatory=$true)]
17    [ValidateSet("staging", "production")]
18    [string]$Environment,
19    
20    [string]$Version = "latest"
21)
22
23$ErrorActionPreference = "Stop"
24
25function Write-Log {
26    param([string]$Message)
27    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
28    Write-Host "[$timestamp] $Message"
29}
30
31try {
32    Write-Log "Starting deployment to $Environment"
33    Write-Log "Version: $Version"
34    
35    # Deployment logic here
36    
37    Write-Log "Deployment complete!"
38}
39catch {
40    Write-Log "ERROR: $_"
41    exit 1
42}

#Summary

ConceptPowerShell
Variables$name = "value"
Arrays@("a", "b")
Hash tables@{Key="Value"}
Functionsfunction Name { }
PipelineGet-X | Where | Select
RemoteInvoke-Command