๐งฉ 1. What is PowerShell?
- A task automation and configuration management tool.
- Used by IT admins, SREs, and cloud engineers for managing Windows, Azure, and more.
- Works with cmdlets (built-in functions), scripts, REST APIs, and .NET objects.
๐ ๏ธ 2. Basic Structure of a PowerShell Script
# My first script
Write-Host "Hello, world!"
Save as myscript.ps1 and run it in PowerShell.
๐งฑ 3. Core Building Blocks
โ Variables
$name = "Gufran"
$age = 30
โ Strings
Write-Host "Hello, $name"
โ Arrays & Loops
$servers = @("server1", "server2")
foreach ($s in $servers) {
Write-Host "Pinging $s"
}
โ If Conditions
if ($age -gt 18) {
Write-Host "Adult"
} else {
Write-Host "Minor"
}
๐งฐ 4. Functions
function Say-Hello {
param([string]$name)
Write-Host "Hello, $name!"
}
Say-Hello -name "Rahul"
๐ฆ 5. Parameters and Script Arguments
param(
[string]$UserName,
[int]$Age
)
Write-Host "Name: $UserName, Age: $Age"
Run as:
.\myscript.ps1 -UserName "Rahul" -Age 30
๐งช 6. Error Handling
try {
Get-Item "C:\nonexistent.txt"
}
catch {
Write-Host "Error occurred: $($_.Exception.Message)"
}
๐ 7. File Operations
# Read
$content = Get-Content "file.txt"
# Write
Set-Content "file.txt" "New content"
# Append
Add-Content "file.txt" "Additional line"
๐ 8. Calling REST APIs
$token = "Bearer YOUR_TOKEN"
Invoke-RestMethod -Uri "https://api.example.com" -Headers @{Authorization = $token}
๐ง 9. Useful Cmdlets for Admins
| Cmdlet | Use |
|---|---|
Get-Service | View Windows services |
Restart-Service | Restart a service |
Get-Process | View processes |
Start-Process | Launch an app |
Test-Connection | Ping |
Get-EventLog | Read event logs |
Get-AzSqlDatabase | Azure SQL info |
Start-Sleep -Seconds 5 | Pause execution |
๐งพ 10. Commenting Code
# Single-line comment
<#
Multi-line
comment
#>
๐ฆ 11. Modules and Importing
Import-Module Az.Accounts
Install if not present:
Install-Module Az -AllowClobber -Scope CurrentUser
โ๏ธ 12. Running Scripts
Run the script:
.\yourscript.ps1
Allow script execution (once):
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
๐ก๏ธ 13. Best Practices
- Always use parameter validation:
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ServerName
- Use try/catch for all critical tasks
- Comment your code
- Use logging and output clearly
- Avoid hardcoding secrets (use Key Vault or variables)
๐ 14. Practical Script Example for Admins
param(
[string]$ServerName
)
if (Test-Connection -ComputerName $ServerName -Count 1 -Quiet) {
Write-Host "$ServerName is reachable"
} else {
Write-Host "$ServerName is not reachable"
}
๐ง Want to Practice?
Try writing these:
- A script to stop and start a Windows service
- A script to read a list of servers from CSV and ping them
- A script to monitor disk space and send alert if low
?
Category: