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:
---
powershell
→ Enter
# Get current date and time
Get-Date
# List files in current directory
Get-ChildItem
# Get system information
Get-ComputerInfo
---
Get-Date # Same as
get-date # Same as
GET-DATE
# This is a single-line comment
<#
This is a
multi-line comment
#>
# 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 start with $
$name = "John"
$age = 25
$isActive = $true
# Display variable
$name
Write-Host $name
# 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
$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 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
# 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
---
# 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
# -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
---
# Get process object
$proc = Get-Process -Name "notepad"
# Access properties
$proc.Name
$proc.Id
$proc.WorkingSet
$proc.StartTime
# See all properties
$proc | Get-Member
# 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
---
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
# $_ 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"
}
---
# Simple array
$fruits = @("apple", "banana", "cherry")
# Mixed types
$mixed = @("text", 42, $true, (Get-Date))
# Empty array
$empty = @()
# Range
$numbers = 1..10
# 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
---
# 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
---
$age = 25
if ($age -ge 18) {
Write-Host "Adult"
} elseif ($age -ge 13) {
Write-Host "Teenager"
} else {
Write-Host "Child"
}
-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)
$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
---
# 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 ($i = 1; $i -le 10; $i++) {
Write-Host "Count: $i"
}
$count = 1
while ($count -le 5) {
Write-Host "Count: $count"
$count++
}
---
function Say-Hello {
Write-Host "Hello, World!"
}
# Call the function
Say-Hello
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
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"
}
}
---
# 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
# 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"
---
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"
}
# 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
---
# 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"
# 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
---
# 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
---
Get-ComputerInfo # System details
Get-WmiObject Win32_OperatingSystem # OS info
Get-EventLog -LogName System -Newest 10 # Recent system events
Test-NetConnection google.com -Port 80 # Test connectivity
Get-NetAdapter # Network adapters
ipconfig # IP configuration (external command)
# 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"
---
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
---
Press Tab
to auto-complete commands, parameters, and file paths.
Always test destructive commands with -WhatIf
first:
Remove-Item C:\temp\* -WhatIf
try {
# Risky operation
} catch {
Write-Error "Something went wrong: $($_.Exception.Message)"
}
# This function checks Oracle connectivity
function Test-OracleConnection {
# Implementation here
}
# Good
$oracleServerName = "ORAPROD01"
# Bad
$x = "ORAPROD01"
---
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
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!