PowerShell Basics Guide¶
Category: PowerShell Fundamentals Tags: PowerShell basics, scripting, command line, system administration, beginner 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: - Works with objects (not just text) - Built-in help system - Powerful scripting capabilities - Cross-platform (Windows, Linux, macOS)
PowerShell Environment Setup¶
Launching PowerShell¶
- Windows: Start Menu → Type "PowerShell" → Run as Administrator (for system tasks)
- Alternative: Win+R → type
powershell→ Enter
Essential First Commands¶
# Get current date and time
Get-Date
# List files in current directory
Get-ChildItem
# Get system information
Get-ComputerInfo
Fundamental Syntax Concepts¶
Case Sensitivity Rules¶
Code Documentation¶
Multi-Line Commands¶
# 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
Variable Management¶
Variable Declaration¶
# Variables start with $
$name = "John"
$age = 25
$isActive = $true
# Display variable
$name
Write-Host $name
Data Type Specification¶
# 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
Built-in System 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
PowerShell Cmdlets¶
Command Naming Convention¶
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
Standard Action Verbs¶
- Get: Retrieve information
- Set: Modify something
- New: Create something
- Remove: Delete something
- Start/Stop: Control services/processes
- Test: Check conditions
- Import/Export: Work with data
Help System Usage¶
# 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
Command Parameters¶
Parameter Fundamentals¶
# 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
Standard Parameter Types¶
# -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
Object-Oriented Concepts¶
Object-Based Architecture¶
# Get process object
$proc = Get-Process -Name "notepad"
# Access properties
$proc.Name
$proc.Id
$proc.WorkingSet
$proc.StartTime
# See all properties
$proc | Get-Member
Property Manipulation¶
# 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
Pipeline Operations¶
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 Object References¶
# $_ 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"
}
Data Collections¶
Array Declaration¶
# Simple array
$fruits = @("apple", "banana", "cherry")
# Mixed types
$mixed = @("text", 42, $true, (Get-Date))
# Empty array
$empty = @()
# Range
$numbers = 1..10
Array Manipulation¶
# 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 Table Operations¶
Hash Table Declaration¶
# 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
Decision Making Structures¶
Conditional Statements¶
$age = 25
if ($age -ge 18) {
Write-Host "Adult"
} elseif ($age -ge 13) {
Write-Host "Teenager"
} else {
Write-Host "Child"
}
Logical 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)
Practical 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
Iteration Structures¶
ForEach Iteration¶
# 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"
}
Numeric For Loop¶
Conditional While Loop¶
Function Development¶
Simple Function Creation¶
Parameterized Functions¶
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 Features¶
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 System Management¶
Essential 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
File Content Operations¶
# 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"
Exception Management¶
Structured Error Handling¶
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 Response Configuration¶
# 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
System Service and Process Management¶
Windows Service Control¶
# 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"
Process Management¶
# 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
PowerShell Module System¶
Module Import and Usage¶
# 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
Essential Administrative Commands¶
System Status Commands¶
Get-ComputerInfo # System details
Get-WmiObject Win32_OperatingSystem # OS info
Get-EventLog -LogName System -Newest 10 # Recent system events
Network Diagnostic Commands¶
Test-NetConnection google.com -Port 80 # Test connectivity
Get-NetAdapter # Network adapters
ipconfig # IP configuration (external command)
Registry Access Commands¶
# 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"
Script Security 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
Development Best Practices¶
Tab Completion Usage¶
Press Tab to auto-complete commands, parameters, and file paths.
Development Environment Selection¶
- PowerShell ISE: Built-in editor with IntelliSense
- VS Code: Modern editor with PowerShell extension
Safe Command Testing¶
Always test destructive commands with -WhatIf first:
Error Handling Implementation¶
Code Documentation Standards¶
Variable Naming Conventions¶
Command Quick Reference¶
Core PowerShell 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
Productivity Shortcuts¶
Tab: Auto-completeCtrl+C: Stop current commandCtrl+L: Clear screenF7: Command historyUp/Down arrows: Previous/next commandCtrl+R: Search command history
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!