Introduction
Modules help you organize your PowerShell scripts into reusable packages. They make sharing and using your code easier.
New-Module -ScriptBlock { <commands> }
# Or create a .psm1 file with functions and import it using Import-Module# 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
# 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
# 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"
MyModule.psm1 with function Get-Greeting defined as:function Get-Greeting { "Hello, World!" }Import-Module .\MyModule.psm1
Get-Greeting
Utils.psm1 with a function but when you run Import-Module .\Utils.psm1, you get an error: "Cannot load module because of a syntax error." What is a common cause?Get-DateInfo and Get-UserInfo. Which is the correct way to organize and import these functions?Pass the test and this pattern moves unknown