SoFunction
Updated on 2025-03-09

Examples of writing and using script modules in the PowerShell tutorial

Now you can manage large, distributed software systems in PowerShell command lines or scripts by writing modules, just like Exchange Server and SharePoint Server are doing. Do you have such a need?

Modules, script modules

Modules are concepts introduced in PowerShell V2 to improve the previously proposed "snap unit". After the management unit is also processed as a module (binary module), PowerShell includes two modules - script module and binary module. So what is a module? A module is a package containing some PowerShell commands and items, which are distributed, shared and loaded as a whole.

Script modules are concepts proposed in PowerShell V2 with modules. They are written entirely by PowerShell syntax and environment and do not need to switch to other compiled languages ​​or development environments. Script modules are the recommended method when writing PowerShell modules now, so you must learn them well.

Writing script modules

Writing script modules includes determining module paths, creating module folders, writing module files, and writing Manifest files. They are all very easy to operate. The specific content is as follows:

Module installation path

In theory, modules can be placed anywhere on the machine, but if placed within the Env:\PSModulePath search range, it will be easier to manage and use. Env:\PSModulePath is a variable with the same modeling method as the system variable %Path%, whose variable value is a string composed of comma-separated paths. Although there are two predefined directories in the env:PSModulePath variable, they may not be created and need to be created when used.

You can obtain two paths with the following command:

Copy the codeThe code is as follows:

PS C:\Users\luke> $paths = (dir Env:\PSModulePath).(";")
PS C:\Users\luke> $paths
C:\Users\luke\Documents\WindowsPowerShell\Modules
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

To check whether the path has been created, you can use the following command:
Copy the codeThe code is as follows:

PS C:\Users\luke> Test-Path -Path $paths[0]
False

If the above returns False, it means that the path has not been created. To create a path, you can use the file browser, the Cmd command, or the PowerShell command. Here, use the PowerShell command as follows:
Copy the codeThe code is as follows:

New-Item -Path $paths[0] -ItemType directory  -Force

In this way, the path required to place the module is created and you can proceed to the next step.

Module folder

The module folder is an integral part of a module and must have the same name as the module. The module files, description files and other possible script files contained in the module must be placed in this folder. For example, this article needs to create module ModuleDemo1, you can use the above new-item command or switch to the script path and use the md command, that is, md ModuleDemo1.

Script module file

The script module file is similar to the general script file content, except that the suffix is ​​.psm1 instead of .ps1, and its file name is the module name. However, generally speaking, the module should only contain definitions of functions, alias, variables, etc., and there should not be many operations or outputs. A simple example of ModuleDemo1.psm1 is as follows:

Copy the codeThe code is as follows:

function Greet([String] name)
{
    "Hello $name"
}

Module description file

The description file is also called the Manifest file, with an extension of .psd1, and its file name must also be the same as the module. Its content is actually a Hashtable; the difference is that the name of the middle key of this Hashtable is predefined by the system. The function of script module files is mainly to limit the running environment, set dependencies and describe scripts.

Creating and editing module description files can be done using any text editor, but for the first time using the recommended command. The command to create a module description file is as follows:

Copy the codeThe code is as follows:

PS C:\Users\luke\Documents\WindowsPowerShell\Modules\ModuleDemo1> New-ModuleManifest -Path .\ModuleDemo1.psd1

cmdlet New-ModuleManifest at command pipeline position 1
Supply values for the following parameters:
NestedModules[0]:
Author: Luke Zhang
CompanyName: CaiJu
Copyright:
ModuleToProcess: ModuleDemo1
Description: Demo1
TypesToProcess[0]:
FormatsToProcess[0]:
RequiredAssemblies[0]:
FileList[0]:

In this way, the module description file is created and the detailed information can be opened and edited.

Using script module

After the script module is written, it can be used. The script module file is loaded and used mainly using the Get-Module command and the Import-Module command. Execute the following command to display the module we just wrote:

Copy the codeThe code is as follows:

PS D:\> Get-Module -ListAvailable

ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Manifest   ModuleDemo1               {}
Manifest   ADRMS                     {}
Manifest   AppLocker                 {}
Manifest   BestPractices             {}
Manifest   BitsTransfer              {}
Manifest   PSDiagnostics             {}
Manifest   ServerManager             {}
Manifest   TroubleshootingPack       {}
Manifest   WebAdministration         {}

Then import the module we just wrote:

Copy the codeThe code is as follows:

PS D:\> Import-Module -Name ModuleDemo1

After importing, the Geet function defined in the module can be used:
Copy the codeThe code is as follows:

PS D:\> Greet "Luke"
Hello Luke

If other alias, variables, etc. are defined in the module, they can also be used.

Conclusion

Modules are not only an efficient solution for scripted management of large software, but also a good way to share PowerShell commands. It is one of the few ways PowerShell programmers can showcase their work results, and the most specialized way. So, play with the module and show it to everyone.