Essential PowerShell Commands for Windows: Complete Reference Guide
PowerShell is a powerful command-line shell and scripting language designed especially for system administration. It provides administrators and power users with comprehensive control over Windows systems. This guide covers the most essential PowerShell commands with practical examples.
Getting Started with PowerShell
Opening PowerShell
- Windows Key + X → Windows PowerShell (Admin) - Administrative privileges
- Start Menu → Search “PowerShell” - Regular user mode
- From Command Prompt: Type
powershellto launch
Basic Syntax Understanding
PowerShell uses cmdlets (command-lets) with a Verb-Noun structure:
Get-Process(Get = Verb, Process = Noun)Set-Location(Set = Verb, Location = Noun)
1. File and Directory Management
Navigation Commands
# Get current location
Get-Location
# Shorter alias
pwd
# Change directory
Set-Location C:\Windows
# Shorter alias
cd C:\Windows
# Go back to previous directory
Set-Location -
# Go to home directory
Set-Location ~
cd ~
Listing Files and Directories
# List items in current directory
Get-ChildItem
# Shorter aliases
ls
dir
gci
# List with details
Get-ChildItem -Force -Name
ls -la
# List only directories
Get-ChildItem -Directory
ls -Directory
# List only files
Get-ChildItem -File
ls -File
# List with specific extension
Get-ChildItem *.txt
ls *.ps1
# Recursive listing
Get-ChildItem -Recurse
ls -r
File Operations
# Create new file
New-Item -ItemType File -Name "test.txt"
# Create with content
"Hello World" | Out-File "hello.txt"
# Create new directory
New-Item -ItemType Directory -Name "MyFolder"
mkdir MyFolder
# Copy files
Copy-Item "source.txt" "destination.txt"
cp "source.txt" "destination.txt"
# Copy directories recursively
Copy-Item "C:\Source" "C:\Destination" -Recurse
# Move/Rename files
Move-Item "old.txt" "new.txt"
mv "old.txt" "new.txt"
# Delete files
Remove-Item "file.txt"
rm "file.txt"
del "file.txt"
# Delete directories with contents
Remove-Item "FolderName" -Recurse -Force
rm -rf "FolderName"
File Content Operations
# Display file content
Get-Content "file.txt"
cat "file.txt"
type "file.txt"
# Display first/last lines
Get-Content "file.txt" -Head 10
Get-Content "file.txt" -Tail 5
# Search in files
Select-String -Pattern "error" -Path "*.log"
grep "error" *.log
# Compare files
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt)
2. System Information Commands
Hardware and System Info
# Computer system information
Get-ComputerInfo
# Operating system details
Get-WmiObject -Class Win32_OperatingSystem
gwmi Win32_OperatingSystem
# Hardware information
Get-WmiObject -Class Win32_ComputerSystem
# CPU information
Get-WmiObject -Class Win32_Processor
# Memory information
Get-WmiObject -Class Win32_PhysicalMemory
# Disk space
Get-WmiObject -Class Win32_LogicalDisk
Get-PSDrive
# System uptime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
# Environment variables
Get-ChildItem Env:
$env:PATH
User and Security Information
# Current user
$env:USERNAME
whoami
# User account information
Get-LocalUser
Get-WmiObject -Class Win32_UserAccount
# Group membership
Get-LocalGroup
Get-LocalGroupMember -Group "Administrators"
# Running as administrator check
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
3. Process Management
Process Information
# List all processes
Get-Process
ps
# Specific process
Get-Process -Name "notepad"
ps notepad
# Processes by CPU usage
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
# Processes by memory usage
Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 10
Process Control
# Start process
Start-Process "notepad.exe"
Start-Process "chrome.exe" -ArgumentList "https://google.com"
# Stop process by name
Stop-Process -Name "notepad"
Stop-Process -Name "chrome" -Force
# Stop process by ID
Stop-Process -Id 1234
# Kill all instances
Get-Process -Name "notepad" | Stop-Process -Force
4. Service Management
# List all services
Get-Service
# Services by status
Get-Service | Where-Object Status -eq "Running"
Get-Service | Where-Object Status -eq "Stopped"
# Specific service
Get-Service -Name "Spooler"
# Start/Stop/Restart services (requires admin)
Start-Service -Name "Spooler"
Stop-Service -Name "Spooler"
Restart-Service -Name "Spooler"
# Service details
Get-Service -Name "Spooler" | Format-List *
5. Network Commands
Network Information
# IP configuration
Get-NetIPConfiguration
ipconfig
# Network adapters
Get-NetAdapter
# IP addresses
Get-NetIPAddress
# DNS settings
Get-DnsClientServerAddress
# Route table
Get-NetRoute
route print
Network Testing
# Ping
Test-Connection -ComputerName "google.com"
ping google.com
# Test port connectivity
Test-NetConnection -ComputerName "google.com" -Port 80
Test-NetConnection -ComputerName "google.com" -Port 443
# DNS resolution
Resolve-DnsName "google.com"
nslookup google.com
# Download file
Invoke-WebRequest -Uri "https://example.com/file.txt" -OutFile "file.txt"
wget "https://example.com/file.txt" -OutFile "file.txt"
6. Windows-Specific Commands
Windows Features and Applications
# Open File Explorer
explorer
explorer C:\Windows
# Open specific applications
Start-Process "calc"
Start-Process "mspaint"
Start-Process "notepad"
# Windows features
Get-WindowsOptionalFeature -Online
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-WebServerRole"
Disable-WindowsOptionalFeature -Online -FeatureName "IIS-WebServerRole"
# Installed programs
Get-WmiObject -Class Win32_Product
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*
Registry Operations
# Navigate registry
Set-Location HKLM:\SOFTWARE
# Get registry values
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"
# Create registry key
New-Item -Path "HKCU:\Software\MyApp"
# Set registry value
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Setting" -Value "Value"
# Remove registry key
Remove-Item -Path "HKCU:\Software\MyApp" -Recurse
7. Text Processing and Filtering
Object Manipulation
# Filter objects
Get-Process | Where-Object CPU -gt 100
Get-Service | Where-Object Status -eq "Running"
# Select specific properties
Get-Process | Select-Object Name, CPU, WorkingSet
# Sort objects
Get-Process | Sort-Object CPU -Descending
Get-ChildItem | Sort-Object LastWriteTime
# Group objects
Get-Process | Group-Object ProcessName
# Measure objects
Get-ChildItem | Measure-Object -Property Length -Sum -Average
String Operations
# String formatting
"Hello {0}" -f "World"
"The time is $(Get-Date)"
# String methods
"Hello World".Length
"Hello World".ToUpper()
"Hello World".Split(" ")
"Hello World".Replace("World", "PowerShell")
# Regular expressions
"test@email.com" -match "^\w+@\w+\.\w+$"
"123-456-7890" -replace "-", ""
8. Variables and Output
Variable Operations
# Create variables
$name = "John"
$age = 30
$computers = @("PC1", "PC2", "PC3")
# Use variables
Write-Host "Name: $name, Age: $age"
# Arrays
$fruits = @("apple", "banana", "orange")
$fruits[0] # First item
$fruits.Count # Number of items
# Hash tables
$person = @{
Name = "John"
Age = 30
City = "New York"
}
$person.Name
$person["Age"]
Output Formatting
# Format as table
Get-Process | Format-Table Name, CPU, WorkingSet
# Format as list
Get-Service | Format-List Name, Status, StartType
# Output to file
Get-Process | Out-File "processes.txt"
Get-Service | Export-Csv "services.csv"
Get-Process | ConvertTo-Json | Out-File "processes.json"
# Output to grid view
Get-Process | Out-GridView
Get-Service | Out-GridView
9. Help and Documentation
# Get help for cmdlets
Get-Help Get-Process
Get-Help Get-Process -Examples
Get-Help Get-Process -Detailed
Get-Help Get-Process -Full
# Update help files
Update-Help
# Find commands
Get-Command *process*
Get-Command -Verb Get
Get-Command -Noun Service
# Command aliases
Get-Alias
Get-Alias ls
Get-Alias dir
10. Useful One-Liners
System Maintenance
# Clear temporary files
Get-ChildItem -Path $env:TEMP -Recurse | Remove-Item -Force -Recurse
# Find large files
Get-ChildItem -Recurse | Sort-Object Length -Descending | Select-Object -First 10
# Get installed software
Get-WmiObject -Class Win32_Product | Select-Object Name, Version | Sort-Object Name
# Check disk space
Get-WmiObject -Class Win32_LogicalDisk | Select-Object DeviceID, @{Name="Size(GB)";Expression={[math]::Round($_.Size/1GB,2)}}, @{Name="FreeSpace(GB)";Expression={[math]::Round($_.FreeSpace/1GB,2)}}
# Find empty directories
Get-ChildItem -Recurse -Directory | Where-Object {(Get-ChildItem $_.FullName).Count -eq 0}
Network Diagnostics
# Test multiple hosts
@("google.com", "microsoft.com", "github.com") | ForEach-Object { Test-Connection $_ -Count 1 }
# Get public IP
(Invoke-WebRequest -Uri "http://ifconfig.me/ip").Content
# Check open ports
1..1024 | ForEach-Object { Test-NetConnection -ComputerName "localhost" -Port $_ -InformationLevel Quiet }
# DNS lookup for multiple domains
@("google.com", "microsoft.com") | ForEach-Object { Resolve-DnsName $_ }
11. Advanced PowerShell Features
Execution Policies
# Check current execution policy
Get-ExecutionPolicy
# Set execution policy (requires admin)
Set-ExecutionPolicy RemoteSigned
Set-ExecutionPolicy Unrestricted
Set-ExecutionPolicy Restricted
Modules
# List available modules
Get-Module -ListAvailable
# Import module
Import-Module ModuleName
# Find modules online
Find-Module -Name "*Azure*"
# Install module from PowerShell Gallery
Install-Module -Name ModuleName
Background Jobs
# Start background job
Start-Job -ScriptBlock { Get-Process }
# Get job status
Get-Job
# Receive job results
Receive-Job -Id 1
# Remove completed jobs
Remove-Job -State Completed
Best Practices and Tips
1. Use Tab Completion
PowerShell provides excellent tab completion for cmdlets, parameters, and file paths.
2. Leverage Aliases
Common aliases make commands shorter:
ls=Get-ChildItemcd=Set-Locationpwd=Get-Locationcat=Get-Content
3. Pipeline Power
Use the pipeline to chain commands:
Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5
4. Error Handling
try {
Get-Process -Name "NonExistent" -ErrorAction Stop
} catch {
Write-Error "Process not found"
}
5. Script Execution
Save commands in .ps1 files for reuse:
# Save as script.ps1
Get-Date
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion
# Execute script
.\script.ps1
PowerShell vs Command Prompt
| Feature | PowerShell | Command Prompt |
|---|---|---|
| Object-oriented | Yes | No (text-based) |
| Tab completion | Advanced | Basic |
| Pipeline | Object pipeline | Text pipeline |
| Aliases | Extensive | Limited |
| Scripting | Full language | Batch files |
| .NET integration | Full | None |
Common Troubleshooting
1. Permission Errors
- Run PowerShell as Administrator
- Check execution policies
- Verify user permissions
2. Module Not Found
- Use
Install-Moduleto install missing modules - Check module paths with
$env:PSModulePath
3. Script Won’t Run
- Check execution policy:
Get-ExecutionPolicy - Use full path or
.\for local scripts - Verify file extension is
.ps1
Conclusion
PowerShell is an incredibly powerful tool for Windows system administration and automation. These commands represent the foundation of PowerShell usage, but the platform offers much more through its extensive cmdlet library, scripting capabilities, and .NET integration.
Start with basic file management and system information commands, then gradually explore more advanced features like background jobs, modules, and custom scripts. The consistent verb-noun syntax and comprehensive help system make PowerShell relatively easy to learn while providing enterprise-level capabilities.
Remember to use Get-Help for any cmdlet you’re unfamiliar with, and leverage tab completion to discover available parameters and options. With practice, PowerShell will become an indispensable tool for managing Windows systems efficiently.
Comments