PowerShell Explained — Complete Beginner's Guide
PowerShell is a task automation and configuration management framework from Microsoft, combining a command-line shell with a scripting language built on the .NET runtime.
What You’ll Learn
You’ll master PowerShell cmdlets, the pipeline for chaining commands, file system navigation, script creation, and real-world automation and security scanning tasks.
Why PowerShell Matters
PowerShell is essential for Windows system administration, DevOps, and security professionals. At DodaTech, we use PowerShell scripts to automate Durga Antivirus Pro deployment across thousands of endpoints, manage DodaZIP batch file processing, and scan system logs for security threats. If you work with Windows servers, Office 365, or Azure, PowerShell is non-negotiable.
PowerShell Learning Path
flowchart LR
A[Command Line Basics] --> B[PowerShell]
B --> C[Cmdlets & Aliases]
C --> D[Pipeline & Objects]
D --> E[Scripting & Functions]
E --> F[Modules & Remoting]
F --> G[Automation & Security]
B:::current
classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
What Makes PowerShell Different
Most shells (like Bash or Command Prompt) work with text. Commands output text, and you parse that text to extract information.
PowerShell works with objects. Every command outputs structured data (.NET objects) with properties and methods. This is a fundamentally different and more powerful approach.
Think of it this way:
- Bash: You get a text file listing. To find a file by size, you parse columns with
awkorcut - PowerShell: You get file objects. To find a file by size, you filter by the
Lengthproperty
# Bash: Parse text to get file sizes
ls -la | awk '{print $5, $9}'
# PowerShell: Filter by property (cleaner, more reliable)
Get-ChildItem | Where-Object { $_.Length -gt 1MB } | Select-Object Name, LengthCmdlets: The Building Blocks
Cmdlets (pronounced “command-lets”) are PowerShell commands named with a Verb-Noun pattern:
| Verb | Noun | Cmdlet | What It Does |
|---|---|---|---|
| Get | Process | Get-Process | Lists running processes |
| Stop | Service | Stop-Service | Stops a Windows service |
| Set | Location | Set-Location | Changes directory |
| Copy | Item | Copy-Item | Copies files/folders |
| Remove | Item | Remove-Item | Deletes files/folders |
This consistent naming makes PowerShell self-documenting. If you want to work with something, guess Get-Verb-Noun and you’ll probably be right.
Common Cmdlets to Get Started
# File system navigation
Get-Location # Show current directory (like pwd)
Set-Location C:\Data # Change to C:\Data (like cd)
Get-ChildItem # List items in directory (like ls/dir)
Get-ChildItem -Recurse # List all items recursively
# File operations
New-Item -Name "test.txt" -ItemType "file" # Create a file
New-Item -Name "Backup" -ItemType "directory" # Create a folder
Copy-Item "source.txt" "destination.txt" # Copy a file
Move-Item "old.txt" "new.txt" # Rename/move a file
Remove-Item "temp.txt" # Delete a file
# System information
Get-Process # Running processes
Get-Service # Windows services
Get-EventLog -LogName System -Newest 10 # Last 10 system eventsThe Pipeline: | (Pipe)
The pipeline is PowerShell’s superpower. It passes objects from one cmdlet to the next:
# Get all running processes, filter by name, sort by memory usage
Get-Process | Where-Object { $_.ProcessName -like "chrome*" } | Sort-Object WorkingSet -Descending | Select-Object ProcessName, WorkingSetBreaking this down:
Get-Process— gets all running processes (as objects)Where-Object { $_.ProcessName -like "chrome*" }— filters to only Chrome processesSort-Object WorkingSet -Descending— sorts by memory usage (largest first)Select-Object ProcessName, WorkingSet— shows only name and memory columns
Expected output (simplified):
ProcessName WorkingSet
----------- ----------
chrome 1258291200
chrome 987654321
chrome 654321000PowerShell Scripting
Scripts save commands in .ps1 files. Let’s write one that monitors a folder for new files:
# FileMonitor.ps1 - Monitor a folder for new files
param(
[string]$Path = "C:\Temp\Monitor",
[int]$Minutes = 5
)
# Create the folder if it doesn't exist
if (-not (Test-Path $Path)) {
New-Item -Path $Path -ItemType "directory" -Force
Write-Host "Created monitoring folder: $Path" -ForegroundColor Green
}
Write-Host "Monitoring $Path for new files every $Minutes minute(s)..." -ForegroundColor Cyan
# Get current files
$knownFiles = Get-ChildItem -Path $Path | ForEach-Object { $_.FullName }
while ($true) {
Start-Sleep -Seconds ($Minutes * 60)
$currentFiles = Get-ChildItem -Path $Path | ForEach-Object { $_.FullName }
$newFiles = $currentFiles | Where-Object { $_ -notin $knownFiles }
if ($newFiles.Count -gt 0) {
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - New files detected:" -ForegroundColor Yellow
foreach ($file in $newFiles) {
$item = Get-Item $file
Write-Host " → $file ($([math]::Round($item.Length / 1KB, 2)) KB)" -ForegroundColor Green
}
$knownFiles = $currentFiles
}
else {
Write-Host "$(Get-Date -Format 'HH:mm:ss') - No new files" -ForegroundColor DarkGray
}
}What’s happening:
param()defines script parameters with defaultsTest-Pathchecks if a folder exists (returns true/false)Write-Hostoutputs colored text to the console$knownFilesstores the initial list of files- The
while ($true)loop runs indefinitely Start-Sleeppauses for the specified intervalWhere-Object { $_ -notin $knownFiles }finds files not in our known listGet-Date -Format 'yyyy-MM-dd HH:mm:ss'formats the timestamp
Working with CSV and Data
PowerShell excels at data processing:
# Create and export data
$computers = @(
[PSCustomObject]@{ Name = "DC-01"; CPU = 45; Memory = 70; Disk = 55; Status = "Online" }
[PSCustomObject]@{ Name = "WEB-01"; CPU = 23; Memory = 45; Disk = 80; Status = "Online" }
[PSCustomObject]@{ Name = "DB-01"; CPU = 67; Memory = 90; Disk = 65; Status = "Degraded" }
[PSCustomObject]@{ Name = "APP-01"; CPU = 12; Memory = 30; Disk = 45; Status = "Offline" }
)
# Export to CSV
$computers | Export-Csv -Path "server_status.csv" -NoTypeInformation
# Read CSV back
$imported = Import-Csv -Path "server_status.csv"
# Filter and report
$critical = $imported | Where-Object { [int]$_.Memory -gt 80 -or [int]$_.CPU -gt 60 }
Write-Host "Critical Servers:" -ForegroundColor Red
$critical | Format-Table Name, CPU, Memory, StatusExpected output:
Critical Servers:
Name CPU Memory Status
---- --- ------ ------
DC-01 45 70 Online
DB-01 67 90 Degraded
APP-01 12 30 OfflineSecurity Angle: PowerShell for Security Scanning
PowerShell is widely used in security operations. Here’s a script that detects suspicious files:
# SecurityScanner.ps1
param([string]$ScanPath = "C:\Users")
Write-Host "Security Scan Started: $(Get-Date)" -ForegroundColor Cyan
Write-Host "Scanning: $ScanPath" -ForegroundColor Cyan
# Detect files with suspicious double extensions
$suspiciousExtensions = @("*.exe.vbs", "*.exe.js", "*.pdf.exe", "*.docm")
$suspiciousFiles = @()
foreach ($pattern in $suspiciousExtensions) {
$files = Get-ChildItem -Path $ScanPath -Filter $pattern -Recurse -ErrorAction SilentlyContinue
$suspiciousFiles += $files
}
if ($suspiciousFiles.Count -gt 0) {
Write-Host "WARNING: Found $($suspiciousFiles.Count) suspicious files!" -ForegroundColor Red
$suspiciousFiles | Format-Table FullName, Length, LastWriteTime
}
else {
Write-Host "No suspicious files found." -ForegroundColor Green
}
# Check for recently modified executables
$recentExes = Get-ChildItem -Path $ScanPath -Filter "*.exe" -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) }
if ($recentExes.Count -gt 0) {
Write-Host "Recently modified executables ($($recentExes.Count) found):" -ForegroundColor Yellow
$recentExes | Select-Object FullName, LastWriteTime | Format-Table
}
Write-Host "Security Scan Complete: $(Get-Date)" -ForegroundColor CyanSecurity scanning patterns:
- Double extensions like
invoice.pdf.exeare a classic malware technique - Checking recently modified executables can detect ransomware activity
Get-ChildItem -Recurseis the standard API for crawling directories-ErrorAction SilentlyContinueprevents permission errors from stopping the scan
Durga Antivirus Pro uses similar PowerShell-based scanning as a lightweight first-pass detection layer before its deep learning engine takes over.
Common Mistakes Beginners Make
- Confusing PowerShell with Command Prompt:
dirin CMD is text output.dirin PowerShell isGet-ChildItemwith objects. - Forgetting
$_: The current pipeline object is represented by$_.Where-Object { $_.Name -eq "test" }is the pattern. - Using
=instead of-eq: PowerShell uses-eqfor comparison (not==) and=for assignment. - Not using
Select-Object -ExpandProperty: If you need a single property’s values, useSelect-Object -ExpandProperty Name. - Forgetting
-Recurse:Get-ChildItemonly gets top-level items unless you add-Recurse. - Overcomplicating with
ForEach-Object: OftenWhere-Object+Select-Objectis more readable than a custom loop. - Not using
-Filter: Filtering withWhere-Objectis flexible but slower. Use-Filter "*.txt"onGet-ChildItemfor performance.
Practice Questions
- What naming convention do PowerShell cmdlets use?
- What does the pipeline (
|) pass between commands? - What does
$_represent in the pipeline? - How do you check if a file exists in PowerShell?
- How is PowerShell different from Command Prompt?
Answers:
- Verb-Noun (e.g.,
Get-Process,Stop-Service,Copy-Item). - Objects (.NET objects with properties and methods), not text strings.
- The current object in the pipeline (like “this” or “it”).
- Use
Test-Path "file.txt"— it returns$trueor$false. - PowerShell works with objects and is scriptable; Command Prompt works with text and has very limited scripting.
Challenge
Create a script that monitors the Windows Event Log for security events (Event ID 4625 = failed logon). If there are more than 10 failed logons in 5 minutes, write a warning to a log file and send an email alert (simulate by writing to a file).
Real-World Task
Build a server inventory script that:
- Connects to a list of remote computers (or localhost for testing)
- Collects: OS version, uptime, CPU/memory/disk usage, installed software list
- Exports the results to a CSV file with a timestamp
- Highlights servers below 10% free disk space
Featured Snippet
What is PowerShell?
PowerShell is a task automation framework from Microsoft combining a command-line shell and scripting language that processes structured objects (not text) through a pipeline, built on the .NET runtime for system administration and automation.
FAQ
Try It Yourself
What’s Next
What’s Next
Congratulations on completing this Powershell tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro