PowerShell Guide

Table of Contents

Introduction to PowerShell

PowerShell is a task automation framework and command-line shell from Microsoft, designed especially for system administrators. It combines the flexibility of scripting with the power of a full programming language.

Key Features:

PowerShell Basics

Cmdlets

Cmdlets are lightweight commands following the verb-noun naming pattern:


# Get running processes
Get-Process

# Stop a specific service
Stop-Service -Name "ServiceName"

# Get system information
Get-ComputerInfo
    

Pipeline

PowerShell's pipeline passes objects, not text:


# Get processes using more than 100MB RAM
Get-Process | Where-Object { $_.WorkingSet -gt 100MB } | Sort-Object WorkingSet -Descending

# Export results to CSV
Get-Service | Export-Csv -Path "services.csv"
    

Scripting Fundamentals

Variables


# Variable declaration
$name = "John"
$age = 30
$isAdmin = $true

# Arrays
$numbers = @(1, 2, 3, 4, 5)
$fruits = "apple", "banana", "orange"

# Hash tables
$user = @{
    Name = "John Doe"
    Role = "Administrator"
    Department = "IT"
}
    

Control Structures


# If statement
if ($age -gt 18) {
    Write-Output "Adult"
} else {
    Write-Output "Minor"
}

# ForEach loop
foreach ($item in $collection) {
    Write-Output $item
}

# While loop
while ($condition) {
    # Do something
}
    

Modules and Functions

Working with Modules


# List available modules
Get-Module -ListAvailable

# Import a module
Import-Module ActiveDirectory

# Find commands in a module
Get-Command -Module ActiveDirectory
    

Creating Functions


function Get-UserInfo {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Username
    )
    
    try {
        Get-ADUser -Identity $Username
    } catch {
        Write-Error "User not found"
    }
}
    

System Administration

Active Directory Management


# Create new user
New-ADUser -Name "John Doe" `
           -SamAccountName "jdoe" `
           -UserPrincipalName "jdoe@domain.com" `
           -Enabled $true

# Add user to group
Add-ADGroupMember -Identity "IT Department" -Members "jdoe"

# Get user properties
Get-ADUser -Identity "jdoe" -Properties *
    

File System Operations


# Create directory
New-Item -Path "C:\Logs" -ItemType Directory

# Copy files
Copy-Item -Path "C:\Source\*" -Destination "D:\Backup" -Recurse

# Get file information
Get-ChildItem -Path "C:\Users" -Recurse | Where-Object { $_.Length -gt 100MB }
    

Automation and Tasks

Scheduled Tasks


# Create scheduled task
$trigger = New-ScheduledTaskTrigger -Daily -At 3AM
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument 'C:\Scripts\Backup.ps1'
Register-ScheduledTask -TaskName "Daily Backup" -Trigger $trigger -Action $action
    

Remote Management


# Enable remote management
Enable-PSRemoting

# Execute command on remote computer
Invoke-Command -ComputerName "Server01" -ScriptBlock { Get-Service }

# Start remote session
Enter-PSSession -ComputerName "Server01"
    

Best Practices

Coding Standards:

Error Handling


try {
    # Potentially dangerous operation
    Remove-Item -Path "C:\ImportantFile.txt" -ErrorAction Stop
} catch {
    Write-Error "Failed to remove file: $_"
} finally {
    # Cleanup code
}
    

Security Considerations

Execution Policy


# Get current execution policy
Get-ExecutionPolicy

# Set execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    
Security Best Practices:

Secure Credential Handling


# Convert secure string
$securePassword = ConvertTo-SecureString "Password123" -AsPlainText -Force

# Create credential object
$credential = New-Object System.Management.Automation.PSCredential("username", $securePassword)

# Use credential in command
Invoke-Command -ComputerName "Server01" -Credential $credential -ScriptBlock { Get-Process }