PowerShell Basics Guide

What is PowerShell?

PowerShell is a command-line shell and scripting language built on .NET. Unlike traditional command prompts that work with text, PowerShell works with objects, making it much more powerful for system administration and automation.

Key differences from Command Prompt:

---

Getting Started

Opening PowerShell

Your First Commands


# Get current date and time
Get-Date

# List files in current directory
Get-ChildItem

# Get system information
Get-ComputerInfo

---

Basic Syntax Rules

Case Insensitive


Get-Date        # Same as
get-date        # Same as
GET-DATE

Comments


# This is a single-line comment

<#
This is a
multi-line comment
#>

Line Continuation


# Use backtick to continue on next line
Get-Process `
  -Name "notepad" `
  -ErrorAction SilentlyContinue

# Or use natural breaking points
Get-Process |
  Where-Object { $_.Name -eq "notepad" } |
  Stop-Process

---

Variables

Creating Variables


# Variables start with $
$name = "John"
$age = 25
$isActive = $true

# Display variable
$name
Write-Host $name

Variable Types


# PowerShell auto-detects types, but you can specify
[string]$text = "Hello World"
[int]$number = 42
[bool]$flag = $false
[array]$list = @("apple", "banana", "cherry")
[hashtable]$config = @{server="localhost"; port=1521}
[datetime]$now = Get-Date

Special Variables


$env:USERNAME        # Current username
$env:COMPUTERNAME    # Computer name
$env:TEMP           # Temp directory path
$PWD                # Current working directory
$HOME               # User home directory
$_                  # Current object in pipeline
$?                  # Success of last command (True/False)
$LastExitCode       # Exit code of last command

---

Commands (Cmdlets)

Verb-Noun Structure

PowerShell commands follow a Verb-Noun pattern:


Get-Process         # Get running processes
Stop-Service        # Stop a service
New-Item           # Create new file/folder
Remove-Item        # Delete file/folder
Set-Location       # Change directory
Test-Path          # Check if path exists

Common Verbs

Getting Help


# Get help for any command
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Help Get-Process -Full

# List all commands containing "process"
Get-Command *process*

# Get command syntax
Get-Command Get-Process -Syntax

---

Parameters

Basic Parameter Usage


# Positional parameters (order matters)
Get-ChildItem C:\temp

# Named parameters (clearer)
Get-ChildItem -Path C:\temp -Recurse

# Short form (if unambiguous)
Get-ChildItem -Path C:\temp -R

# Multiple values
Get-Process -Name notepad, calc, explorer

Common Parameter Patterns


# -WhatIf: Preview what would happen (safe testing)
Remove-Item C:\temp\test.txt -WhatIf

# -Confirm: Ask before executing
Remove-Item C:\temp\test.txt -Confirm

# -Force: Override protections
Remove-Item C:\temp\readonly.txt -Force

# -Recurse: Include subdirectories
Get-ChildItem C:\temp -Recurse

# -ErrorAction: Control error handling
Get-Process -Name "nonexistent" -ErrorAction SilentlyContinue

---

Objects and Properties

Everything is an Object


# Get process object
$proc = Get-Process -Name "notepad"

# Access properties
$proc.Name
$proc.Id
$proc.WorkingSet
$proc.StartTime

# See all properties
$proc | Get-Member

Working with Object Properties


# Select specific properties
Get-Process | Select-Object Name, Id, WorkingSet

# Filter objects
Get-Process | Where-Object { $_.WorkingSet -gt 100MB }

# Sort objects
Get-Process | Sort-Object WorkingSet -Descending

---

Pipelines

The pipeline (|) passes objects from one command to the next:


# Basic pipeline
Get-Process | Sort-Object Name

# Complex pipeline
Get-ChildItem C:\temp |
  Where-Object { $_.Extension -eq ".txt" } |
  Sort-Object Length -Descending |
  Select-Object Name, Length |
  Format-Table -AutoSize

Pipeline Variables


# $_ represents current object in pipeline
Get-Process | Where-Object { $_.Name -like "*chrome*" }

# Multiple conditions
Get-ChildItem | Where-Object { 
  $_.Length -gt 1MB -and $_.Extension -eq ".log" 
}

---

Arrays and Collections

Creating Arrays


# Simple array
$fruits = @("apple", "banana", "cherry")

# Mixed types
$mixed = @("text", 42, $true, (Get-Date))

# Empty array
$empty = @()

# Range
$numbers = 1..10

Working with Arrays


# Access elements
$fruits[0]          # First element: "apple"
$fruits[-1]         # Last element: "cherry"
$fruits[1,2]        # Multiple elements

# Array properties
$fruits.Count       # Number of elements
$fruits.Length      # Same as Count

# Add elements
$fruits += "orange"

# Check if element exists
"apple" -in $fruits

---

Hash Tables (Dictionaries)

Creating Hash Tables


# Basic hash table
$person = @{
  Name = "John"
  Age = 30
  City = "New York"
}

# Access values
$person["Name"]
$person.Name        # Same as above

# Add/modify
$person["Email"] = "john@example.com"
$person.Age = 31

# Get all keys/values
$person.Keys
$person.Values

---

Conditional Logic

If Statements


$age = 25

if ($age -ge 18) {
  Write-Host "Adult"
} elseif ($age -ge 13) {
  Write-Host "Teenager"
} else {
  Write-Host "Child"
}

Comparison Operators


-eq     # Equal
-ne     # Not equal
-gt     # Greater than
-ge     # Greater than or equal
-lt     # Less than
-le     # Less than or equal
-like   # Wildcard matching
-match  # Regex matching
-in     # Contains (for arrays)

Examples


$name = "John"
$name -eq "John"        # True
$name -like "J*"        # True (starts with J)
$name -match "^J"       # True (regex: starts with J)

$numbers = 1..10
5 -in $numbers          # True

---

Loops

ForEach Loop


# ForEach with array
$fruits = @("apple", "banana", "cherry")
foreach ($fruit in $fruits) {
  Write-Host "I like $fruit"
}

# ForEach with pipeline
Get-Process | ForEach-Object {
  Write-Host "$($_.Name) uses $($_.WorkingSet) bytes"
}

For Loop


for ($i = 1; $i -le 10; $i++) {
  Write-Host "Count: $i"
}

While Loop


$count = 1
while ($count -le 5) {
  Write-Host "Count: $count"
  $count++
}

---

Functions

Basic Function


function Say-Hello {
  Write-Host "Hello, World!"
}

# Call the function
Say-Hello

Function with Parameters


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

# Call with parameter
Say-HelloTo -Name "John"
Say-HelloTo "John"      # Positional
Say-HelloTo             # Uses default

Advanced Function


function Get-FileInfo {
  param(
    [Parameter(Mandatory=$true)]
    [string]$Path,
    
    [switch]$IncludeHidden
  )
  
  if (Test-Path $Path) {
    $files = Get-ChildItem -Path $Path
    if ($IncludeHidden) {
      $files = $files | Where-Object { $_.Attributes -match "Hidden" }
    }
    return $files
  } else {
    Write-Error "Path not found: $Path"
  }
}

---

File Operations

Basic File Operations


# Check if file/folder exists
Test-Path "C:\temp\file.txt"

# Create folder
New-Item -Path "C:\temp\newfolder" -ItemType Directory

# Create file
New-Item -Path "C:\temp\file.txt" -ItemType File

# Copy file
Copy-Item "source.txt" "destination.txt"

# Move/rename file
Move-Item "old.txt" "new.txt"

# Delete file
Remove-Item "file.txt"

# Delete folder and contents
Remove-Item "folder" -Recurse -Force

Reading and Writing Files


# Read entire file
$content = Get-Content "file.txt"

# Read as single string
$content = Get-Content "file.txt" -Raw

# Write to file (overwrites)
"Hello World" | Out-File "output.txt"

# Append to file
"New line" | Add-Content "output.txt"

# Write array to file
$data = @("Line 1", "Line 2", "Line 3")
$data | Out-File "output.txt"

---

Error Handling

Try-Catch-Finally


try {
  $result = 1 / 0  # This will cause an error
  Write-Host "Result: $result"
} catch {
  Write-Host "An error occurred: $($_.Exception.Message)"
} finally {
  Write-Host "This always runs"
}

Error Action Preferences


# Stop on any error
$ErrorActionPreference = "Stop"

# Continue on errors (default)
$ErrorActionPreference = "Continue"

# Be silent about errors
$ErrorActionPreference = "SilentlyContinue"

# Per-command error handling
Get-Process -Name "nonexistent" -ErrorAction SilentlyContinue

---

Working with Services and Processes

Services


# List all services
Get-Service

# Get specific service
Get-Service -Name "Spooler"

# Start/stop service
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"

# Restart service
Restart-Service -Name "Spooler"

Processes


# List all processes
Get-Process

# Get specific process
Get-Process -Name "notepad"

# Kill process
Stop-Process -Name "notepad"
Stop-Process -Id 1234

# Start process
Start-Process "notepad.exe"
Start-Process "calc.exe" -WindowStyle Maximized

---

Modules

Using Modules


# List available modules
Get-Module -ListAvailable

# Import module
Import-Module WebAdministration

# List commands in module
Get-Command -Module WebAdministration

# Check if module is loaded
Get-Module

---

Common Useful Commands

System Information


Get-ComputerInfo        # System details
Get-WmiObject Win32_OperatingSystem  # OS info
Get-EventLog -LogName System -Newest 10  # Recent system events

Network


Test-NetConnection google.com -Port 80  # Test connectivity
Get-NetAdapter          # Network adapters
ipconfig               # IP configuration (external command)

Registry


# Read registry
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"

# Create registry key
New-Item "HKCU:\Software\MyApp"

# Set registry value
Set-ItemProperty "HKCU:\Software\MyApp" -Name "Setting" -Value "Value"

---

Execution Policies

PowerShell has security policies that control script execution:


# Check current policy
Get-ExecutionPolicy

# Common policies:
# Restricted: No scripts (default)
# RemoteSigned: Local scripts OK, remote scripts need signature
# Unrestricted: All scripts allowed

# Change policy (run as Administrator)
Set-ExecutionPolicy RemoteSigned

# Bypass for single session
powershell -ExecutionPolicy Bypass -File script.ps1

---

Tips and Best Practices

1. Use Tab Completion

Press Tab to auto-complete commands, parameters, and file paths.

2. Use ISE or VS Code

3. Test with -WhatIf

Always test destructive commands with -WhatIf first:


Remove-Item C:\temp\* -WhatIf

4. Use Proper Error Handling


try {
  # Risky operation
} catch {
  Write-Error "Something went wrong: $($_.Exception.Message)"
}

5. Comment Your Code


# This function checks Oracle connectivity
function Test-OracleConnection {
  # Implementation here
}

6. Use Meaningful Variable Names


# Good
$oracleServerName = "ORAPROD01"

# Bad
$x = "ORAPROD01"

---

Quick Reference

Essential Commands


Get-Help <command>      # Get help
Get-Command *keyword*   # Find commands
Get-Member             # See object properties/methods
Where-Object { }       # Filter objects
Select-Object          # Choose properties
Sort-Object            # Sort results
Format-Table          # Display as table
Format-List           # Display as list
Measure-Object        # Count, sum, average
Group-Object          # Group by property

Keyboard Shortcuts

---

This guide covers the fundamentals you need to understand and work with PowerShell scripts. Practice these concepts with small examples, and you'll quickly become comfortable reading and modifying PowerShell code!