Basics of Writing PowerShell Scripts


🧩 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

CmdletUse
Get-ServiceView Windows services
Restart-ServiceRestart a service
Get-ProcessView processes
Start-ProcessLaunch an app
Test-ConnectionPing
Get-EventLogRead event logs
Get-AzSqlDatabaseAzure SQL info
Start-Sleep -Seconds 5Pause 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

?

Related Posts

How to install AZ Modules in Power shell. How to Connect Azure from PowerShell?

Determine if the version of PowerShell you’re running meets the minimum requirements before attempting to install the Az PowerShell module. The .NET Framework 4.7.2 or higher is…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x