Functions, Modules & Profiles

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · PowerShell

Functions, Modules & Profiles

Intermediate ⭐ 80 XP ⏱ 16 min #powershell#modules#functions

Package reusable PowerShell into functions and modules, and customize your profile.

📖Theory

Reusable PowerShell starts with functions that take typed parameters. Group related functions into a module (.psm1) so they can be imported and shared. The community registry, the PowerShell Gallery, distributes modules you install with Install-Module.

Your profile script runs at every session start — the place for aliases, default parameters, and helper functions you want always available. $PROFILE holds its path.

🌍Real-World Example
function Get-DiskFreeGB {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory)] [string] $Drive
  )
  $d = Get-PSDrive $Drive
  [math]::Round($d.Free / 1GB, 1)
}

Get-DiskFreeGB -Drive C        # e.g. 84.3

# Install and use a community module
Install-Module Az -Scope CurrentUser
Import-Module Az

# Add to your profile
notepad $PROFILE               # then add aliases/functions
✍️Hands-On Exercise
  1. Write a function with a mandatory parameter and call it.
  2. Add [CmdletBinding()] and use Write-Verbose with the -Verbose switch.
  3. Install a module from the PowerShell Gallery and run one of its cmdlets.
  4. Add a custom alias to your $PROFILE and reload the session.
🧾Cheat Sheet
TaskCommand
Define functionfunction Verb-Noun { param(...) }
Mandatory param[Parameter(Mandatory)]
Cmdlet behavior[CmdletBinding()]
Import moduleImport-Module Name
Install moduleInstall-Module Name
Profile path$PROFILE
List modulesGet-Module -ListAvailable
💬Common Interview Questions
What is a PowerShell module?

A package of related functions, cmdlets, and variables (often a .psm1 file or gallery package) that you import to reuse and share functionality.

What is the $PROFILE and why use it?

A script that runs at the start of every session — used to load aliases, functions, and default settings so your environment is consistent each time.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type