0
0
PowerShellscripting~5 mins

Module creation basics in PowerShell

Choose your learning style9 modes available
Introduction
Modules help you organize your PowerShell scripts into reusable packages. They make sharing and using your code easier.
You want to reuse the same functions in different scripts without copying code.
You want to share your scripts with friends or coworkers in a clean way.
You want to keep your scripts organized and easy to maintain.
You want to load only the code you need when you start PowerShell.
You want to create a library of tools for your daily tasks.
Syntax
PowerShell
New-Module -ScriptBlock { <commands> }
# Or create a .psm1 file with functions and import it using Import-Module
A module is usually a .psm1 file containing functions and code.
Use Import-Module to load your module into the current session.
Examples
This example shows how to write a function in a module file and then import and use it.
PowerShell
# Create a simple module file
function Get-Hello {
    "Hello, world!"
}

# Save this as HelloModule.psm1

# Then import it
Import-Module ./HelloModule.psm1

# Use the function
Get-Hello
This example creates a module in memory, which loads it automatically into the session.
PowerShell
# Create a module on the fly
$mod = New-Module -ScriptBlock {
    function Get-Time {
        Get-Date
    }
    Export-ModuleMember -Function Get-Time
}

# The module is loaded automatically

# Use the function
Get-Time
Sample Program
This script shows how to create a simple module with a greeting function, import it, and call the function with a parameter.
PowerShell
# Create a module file named MyTools.psm1
function Get-Greeting {
    param([string]$Name = "Friend")
    "Hello, $Name!"
}

# Save the above in MyTools.psm1

# Now in PowerShell session:
Import-Module ./MyTools.psm1

# Call the function
Get-Greeting -Name "Alice"
OutputSuccess
Important Notes
Module files must have the extension .psm1 to be recognized as modules.
Place your module files in a folder named after the module for better organization.
Use Export-ModuleMember inside your .psm1 file to control which functions are visible outside.
Summary
Modules package your PowerShell functions for reuse and sharing.
Create a .psm1 file with your functions and import it using Import-Module.
Modules keep your scripts clean and easy to manage.