🟢 1️⃣ Basic Script Structure¶
Create file:
Run:
If execution blocked:
🟢 2️⃣ Variables¶
🟢 3️⃣ Parameters (Command Line Arguments)¶
Run:
🟢 4️⃣ If / Else¶
if ($Age -gt 18) {
Write-Output "Adult"
}
elseif ($Age -eq 18) {
Write-Output "Exactly 18"
}
else {
Write-Output "Minor"
}
Operators:
🟢 5️⃣ Switch¶
🟢 6️⃣ Loops¶
For¶
Foreach¶
While¶
🟢 7️⃣ Functions¶
function Add-Numbers {
param(
[int]$a,
[int]$b
)
return $a + $b
}
$result = Add-Numbers -a 5 -b 3
Write-Output $result
🟢 8️⃣ Arrays¶
Add:
🟢 9️⃣ Hashtable (Dictionary)¶
🟢 🔟 Objects¶
🟢 11️⃣ Reading File Line by Line¶
🟢 12️⃣ Try / Catch (Error Handling)¶
try {
Get-Content "notexist.txt"
}
catch {
Write-Output "File not found"
}
finally {
Write-Output "Done"
}
Force error catching:
🟢 13️⃣ Logging to File¶
🟢 14️⃣ Checking If File Exists¶
🟢 15️⃣ Background Job¶
🟢 16️⃣ REST API Call¶
POST example:
$body = @{
name = "demo"
} | ConvertTo-Json
Invoke-RestMethod -Uri "https://api.example.com" -Method Post -Body $body -ContentType "application/json"
🟢 17️⃣ Working with Services¶
🟢 18️⃣ Scheduled Task (Basic)¶
Register-ScheduledTask -Action (New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\script.ps1") -Trigger (New-ScheduledTaskTrigger -Daily -At 9am) -TaskName "MyTask"
🟢 19️⃣ Script Template (Production Style)¶
Copy this template:
param(
[string]$Environment = "dev"
)
$ErrorActionPreference = "Stop"
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content "app.log" "$timestamp - $Message"
}
try {
Write-Log "Script started for $Environment"
if (-not (Test-Path "config.json")) {
throw "Config file missing"
}
Write-Log "All checks passed"
}
catch {
Write-Log "Error: $_"
}
finally {
Write-Log "Script finished"
}
🟢 20️⃣ Execution Policy Types¶
🟢 21️⃣ Most Used DevOps Commands Inside Scripts¶
Get-ChildItem
Get-Process
Get-Service
Test-Connection
Invoke-RestMethod
Select-String
Test-Path
Start-Service
Stop-Process
🔥 DevOps Practical Mini Example¶
Health check script:
$server = "google.com"
if (Test-Connection $server -Count 2 -Quiet) {
Write-Output "$server is reachable"
}
else {
Write-Output "$server is down"
}