=

Powershell

Introduction to PowerShell

What is PowerShell?

PowerShell is a powerful tool from Microsoft designed for task automation and configuration management. It combines a command-line interface and a scripting language built on the .NET framework.

Why Use PowerShell Scripting?

There are a few key reasons why you might want to use PowerShell:

Setting Up Your Environment

Install Powershell

Run Powershell

PowerShell Basics

Running Commands

You can run different types of command in Powershell, like : Cmdlets (ex: Get-Process), Functions, Scripts (ex: .ps1), Executables (ex: notepad.exe), Aliases (ex: ls), Operators (ex: 7*7) etc.

Writing Your First Script

Comments

Cmdlets

PowerShell cmdlets are built-in commands that follow the naming convention Verb-Noun.

Variables and Data Types

Defining Variables

Variables in PowerShell are prefixed with $ :

Code powershell
$name = "John"
Write-Host "Hello, $name"

Common Data Types

PowerShell is a dynamically typed language and automatically infers data types:

Code powershell
$num = 42        # Integer
$text = "Hello"  # String
$flag = $true    # Boolean

Variable Scopes

Variables can have different scopes (Global, Local, Private, Script):

Code powershell
$global:globalVar = "I am Global"  # Accessible anywhere in the current powershell session
$script:scriptVar = "I am Script Scoped"  # Accessible only within this script

function TestScope {
    $local:localVar = "I am Local"  # Accessible only within this function
    $private:privateVar = "I am Private"  # Not inherited by child scopes

    Write-Host "Inside Function:"       # Inside Function:
    Write-Host "Global: $globalVar"     # Global: I am Global
    Write-Host "Script: $scriptVar"     # Script: I am Script Scoped
    Write-Host "Local: $localVar"       # Local: I am Local
    Write-Host "Private: $privateVar"   # Private: I am Private
}

TestScope

Write-Host "Outside Function:"
Write-Host "Global: $globalVar"  # Global: I am Global
Write-Host "Script: $scriptVar"  # Script: I am Script Scoped
Write-Host "Local: $localVar"  # Not accessible (undefined)
Write-Host "Private: $privateVar"  # Not accessible (undefined)

Conditional Statements

if-else Statements

Used to execute different code blocks based on a condition.

Code powershell
# Syntax of if-else 
if (condition) {
    # code to execute if condition is true
} else {
    # code to execute if condition is false
}

switch Statements

Used to execute different code blocks based on multiple conditions.

Code powershell
# Syntax of switch statement
switch (variable) {
    condition1 { 
        # code to execute if variable matches condition1
    }
    condition2 {
        # code to execute if variable matches condition2  
    }
    default {
        # code to execute if variable doesn't match any condition
    }
}

Loops

for Loop

Executes a block of code a specific number of times.

Code powershell
for ($i = 0; $i -lt 5; $i++) {
    # code to execute in the loop
}

foreach Loop

Iterates over a collection of items and executes a block of code for each item.

Code powershell
$myArray = 1, 2, 3, 4, 5
foreach ($item in $myArray) {
    # code to execute for each item in the array
}

while Loop

Executes a block of code as long as a condition is true.

Code powershell
$counter = 0
while ($counter -lt 5) {
    # code to execute in the loop
    $counter++
}

Functions

Declaring Functions

A function is defined using the function keyword. Example:

Code powershell
function Greet {
    Write-Output "Hello, Welcome to PowerShell!"
}

A function can be run directly into Powershell. To call above function run Greet in powershell.

Function with parameter/s

Using param($PARAMETER1,$PARAMETER2) to take parameters. Example:

Code powershell
function Add-Numbers {
    param([int]$a, [int]$b)
    return $a + $b
}

$result = Add-Numbers -a 5 -b 10
Write-Output "Sum: $result"

Input and Output

Reading User Input

PowerShell provides the Read-Host cmdlet to prompt the user for input.

Code powershell
$name = Read-Host "What is your name?"

Writing to Files

You can use the Out-File cmdlet to write output to a file.

Code powershell
$data | Out-File -FilePath "output.txt"

Redirecting Output

You can use the > operator to redirect output to a file.

Code powershell
Get-Process > processes.txt   # Redirects standard output to a file
Get-Content "nonexistent.txt" 2> error.log  # Redirects error to a file
Get-Process *> alloutput.log   # Redirects all output (success & errors) to a file

Error Handling

Try-Catch-Finally

Used to handle exceptions and errors in your scripts

Code powershell
try {
    # code that might throw an exception
}
catch {
    # code to handle the exception
}
finally {
    # code to execute regardless of whether an exception was thrown
}

$Error Variable

PowerShell maintains an array of recent errors in the $Error variable.

Code powershell
try {
    # code that might throw an exception
}
catch {
    Write-Host "An error occurred: $($_.Exception.Message)"
    $Error[0] # access the most recent error
}

Advanced Topics

Arrays and Hash Tables

Array : An array stores multiple values in a single variable.

Code powershell
$numbers = @(1, 2, 3, 4, 5)
$numbers[0]  # Access first element
$numbers += 6  # Add new element

Hash table : A hash table stores key-value pairs.

Code powershell
$person = @{ Name = "Alice"; Age = 25; Role = "Admin" }
$person["Name"]  # Access value
$person["Age"] = 26  # Modify value

Pipelines

Pipelines (|) pass output from one command as input to another.

Code powershell
Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 5

This gets running processes, sorts by CPU usage, and selects the top 5.