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
Established in 2012, CloudThat is an award-winning company and the first in India to offer cloud training and consulting services for individuals and enterprises worldwide. Recently, it won Google Cloud’s New Training Partner of the Year Award for 2025, becoming the first company in the world in 2025 to hold awards from all three major cloud giants: AWS, Microsoft, and Google. CloudThat notably won consecutive AWS Training Partner of the Year (APJ) awards in 2023 and 2024 and the Microsoft Training Services Partner of the Year Award in 2024, bringing its total award count to an impressive 12 awards in the last 8 years. In addition to this, 20 trainers from CloudThat are ranked among Microsoft’s Top 100 MCTs globally for 2025, demonstrating its exceptional trainer quality on the global stage.
As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, Google Cloud Platform Partner, and collaborator with leading organizations like HPE and Databricks, CloudThat has trained over 850,000 professionals across 600+ cloud certifications, empowering students and professionals worldwide to advance their skills and careers.
WRITTEN BY Naveen H
Comments