Voiced by Amazon Polly |
Introduction
PowerShell isn’t just a scripting language. Whether you’re a sysadmin, DevOps engineer, or automation enthusiast, knowing how to write reusable code using functions, organize your scripts into modules, and troubleshoot effectively will save hours of repetitive work.
Access to Unlimited* Azure Trainings at the cost of 2 with Azure Mastery Pass
- Microsoft Certified Instructor
- Hands-on Labs
- EMI starting @ INR 4999*
PowerShell Functions: Reusable Brilliance
Functions let you encapsulate logic for reuse across scripts.
Basic Function Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function Get-SystemInfo { Write-Output "Computer Name: $env:COMPUTERNAME" Write-Output "OS Version: $(Get-CimInstance Win32_OperatingSystem).Version" Write-Output "Logged In User: $env:USERNAME" } <strong># Call the function</strong> Get-SystemInfo Function with Parameters: powershell CopyEdit function Get-ServiceStatus { param ( [string]$ServiceName ) Get-Service -Name $ServiceName | Select-Object Name, Status } |
# Usage
1 |
Get-ServiceStatus -ServiceName 'wuauserv' |
Creating PowerShell Modules: Organize Like a Pro
Modules help structure your scripts and functions into reusable components.
Step 1: Create a .psm1 File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File: MyTools.psm1 function Get-DiskSpace { Get-PSDrive -PSProvider 'FileSystem' | Select-Object Name, Used, Free } function Restart-SafeService { param([string]$ServiceName) Restart-Service -Name $ServiceName -Force } |
Step 2: Import the Module
# Save the file, then:
1 |
Import-Module "C:\Path\To\MyTools.psm1" |
# Use the functions
1 2 3 |
<strong>Get-DiskSpace</strong> <strong>Restart-SafeService -ServiceName 'Spooler'</strong> |
You can also create a module manifest (.psd1) for advanced features like versioning and dependency management.
Troubleshooting PowerShell Scripts: Common Pitfalls
Troubleshooting PowerShell Scripts: Common Pitfalls
- Use -Verbose and -Debug
1 2 3 4 5 6 7 8 9 10 11 |
function Test-Network { [CmdletBinding()] param([string]$Host) Write-Verbose "Pinging $Host..." Test-Connection $Host -Count 2 } |
Test-Network -Host “google.com” -Verbose
- $Error and Try/Catch for Error Handling
1 2 3 4 5 6 7 8 9 |
try { Get-Item "C:\nonexistent.txt" } catch { Write-Error "File not found: $_" } |
- Check Execution Policy
Scripts not running? Check:
1 2 3 |
Get-ExecutionPolicy Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned |
Some More Examples :
- Function for Recursive Directory Search with Error Handling
This function searches for files within a directory and subdirectories, with error handling for inaccessible paths.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
function Search-DirectoryFiles { param ( [string]$DirectoryPath, [string]$FileType = "*.*" ) if (-not (Test-Path $DirectoryPath)) { Write-Error "The directory path '$DirectoryPath' does not exist." return } try { $files = Get-ChildItem -Path $DirectoryPath -Recurse -Filter $FileType -ErrorAction Stop return $files } catch { Write-Error "Error accessing directory '$DirectoryPath'." } } |
Usage:
1 |
Search-DirectoryFiles -DirectoryPath "C:\Logs" -FileType "*.log" |
This function allows searching recursively and includes error handling for invalid or inaccessible directories.
- PowerShell Module for Disk Space Monitoring (with Exported Data)
This module defines functions for monitoring disk space and exporting the data to a CSV file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# DiskSpaceModule.psm1 function Get-DiskSpace { $drives = Get-PSDrive -PSProvider FileSystem $diskSpaceInfo = $drives | Select-Object Name, @{Name="UsedGB"; Expression={[math]::Round($_.Used / 1GB, 2)}}, @{Name="FreeGB"; Expression={[math]::Round($_.Free / 1GB, 2)}}, @{Name="TotalGB"; Expression={[math]::Round($_.Used / 1GB, 2) + [math]::Round($_.Free / 1GB, 2)}} return $diskSpaceInfo } function Export-DiskSpaceReport { param ( [string]$FilePath = "C:\disk_space_report.csv" ) $diskSpace = Get-DiskSpace $diskSpace | Export-Csv -Path $FilePath -NoTypeInformation Write-Output "Disk space report exported to $FilePath" } |
Usage:
1 2 3 |
Import-Module "C:\Path\To\DiskSpaceModule.psm1" Export-DiskSpaceReport -FilePath "C:\Reports\disk_report.csv" |
This module allows you to monitor and export disk space usage into a CSV for later analysis.
- PowerShell Module for User Management (with Creation and Deletion)
This module provides user management functions for creating and deleting users with validation checks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# UserManagement.psm1 function New-User { param ( [string]$Username, [string]$Password ) if (Get-LocalUser -Name $Username -ErrorAction SilentlyContinue) { Write-Error "User $Username already exists." return } New-LocalUser -Name $Username -Password (ConvertTo-SecureString -AsPlainText $Password -Force) -FullName "$Username User" Write-Output "User $Username created successfully." } function Remove-User { param ( [string]$Username ) if (-not (Get-LocalUser -Name $Username -ErrorAction SilentlyContinue)) { Write-Error "User $Username does not exist." return } Remove-LocalUser -Name $Username Write-Output "User $Username removed successfully." } |
Usage:
1 2 3 4 5 |
Import-Module "C:\Path\To\UserManagement.psm1" New-User -Username "NewUser" -Password "SecureP@ss123" Remove-User -Username "OldUser" |
This module manages user accounts by providing functions for both creating and removing users, with built-in validation to check if the user exists or not.
Conclusion
PowerShell scripting becomes truly powerful when you learn to structure your code with functions and modules, and master troubleshooting techniques.
Enhance Your Productivity with Microsoft Copilot
- Effortless Integration
- AI-Powered Assistance
About CloudThat
CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.
CloudThat is the first Indian Company to win the prestigious Microsoft Partner 2024 Award and is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 850k+ professionals in 600+ cloud certifications and completed 500+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training Partner, AWS Migration Partner, AWS Data and Analytics Partner, AWS DevOps Competency Partner, AWS GenAI Competency Partner, Amazon QuickSight Service Delivery Partner, Amazon EKS Service Delivery Partner, AWS Microsoft Workload Partners, Amazon EC2 Service Delivery Partner, Amazon ECS Service Delivery Partner, AWS Glue Service Delivery Partner, Amazon Redshift Service Delivery Partner, AWS Control Tower Service Delivery Partner, AWS WAF Service Delivery Partner, Amazon CloudFront Service Delivery Partner, Amazon OpenSearch Service Delivery Partner, AWS DMS Service Delivery Partner, AWS Systems Manager Service Delivery Partner, Amazon RDS Service Delivery Partner, AWS CloudFormation Service Delivery Partner, AWS Config, Amazon EMR and many more.
WRITTEN BY Naveen H
Comments