Consider the following module script:
MyWebApp.psm1
:
#Requires -Version 4
#Requires -Modules WebAdministration
function Test-MyWebApp() {
return ((Get-WebApplication 'myapp') -ne $null)
}
(Export-ModuleMember
omitted for simplicity. The script still works as a module without it.)
If this were a ps1
script, the #Requires
comments at the top would force PowerShell to throw an error if
- The version were lower than 4
- The WebAdministration module could not be loaded (imported)
But if I try to import this using Import-Module
, do these have any effect? The #Requires
documentation just says "scripts", but it doesn't clarify whether script modules count as "scripts" or not here. What can I do instead, if not?
No, it's treated as a normal comment
No,
#Requires
comments are not processed when apsm1
script is executed by callingImport-Module
.If we save the script in the question as both
MyWebApp.psm1
andMyWebApp.ps1
on a machine that lacks theWebAdministration
module, we get the following result:Importing the module succeeds, and the function now exists in the current scope. But the function will fail:
Even the
-Version
check is ignored. If we bump it up to 5 on a machine with only PowerShell 4:Use a Module Manifest
The only way to get the requirements validated properly is to use a module manifest. Unfortunately, this must be a separate file alongside the
psm1
file. The following manifest will achieve what the#Requires
comments are intended to do:MyWebApp.psd1
:Importing this file gives the error we want:
Unfortunately, you cannot declare the function in the same file. You must use a separate
psd1
file and then explicitly declare the originalpsm1
script as the "root module." The root module is indicated as a path relative to thepsd1
file.Other attributes:
ModuleVersion
is required. It must be present.PowerShellVersion
accomplishes what#Requires -Version 4
intends.RequiredModules
accomplishes what#Requires -Modules WebAdministration
intends.Note that
Test-MyWebApp
is exported implicitly in both thepsm1
and thepsd1
file. This is normally controlled byExport-ModuleMember -Function
in apsm1
file; the equivalent in a module manifest isFunctionsToExport
. I find it simpler to just omitFunctionsToExport
from the manifest and control what's exported usingExport-ModuleMember
in thepsm1
script.