不,它被视为普通评论
不,通过调用执行脚本#Requires
时不会处理注释。psm1
Import-Module
如果我们将问题中的脚本同时保存在MyWebApp.psm1
缺少MyWebApp.ps1
该WebAdministration
模块的机器上,我们会得到以下结果:
PS> .\MyWebApp.ps1
.\MyWebApp.ps1 : The script 'MyWebApp.ps1' cannot be run because the following modules that are specified by the
"#requires" statements of the script are missing: WebAdministration.
At line:1 char:1
+ .\MyWebApp.ps1
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (MyWebApp.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresMissingModules
PS> Import-Module .\MyWebApp.psm1
PS>
导入模块成功,函数现在存在于当前作用域中。但该功能将失败:
PS> Test-MyWebApp
Get-WebApplication : The term 'Get-WebApplication' is not recognized as the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At .\MyWebApp.psm1:5 char:14
+ return ((Get-WebApplication 'myapp') -Eq $null)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-WebApplication:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
甚至-Version
检查也被忽略。如果我们在一台只有 PowerShell 4 的机器上将它提高到 5:
PS> .\MyWebApp.ps1
.\MyWebApp.ps1 : The script 'MyWebApp.ps1' cannot be run because it contained a "#requires" statement for Windows
PowerShell 5.0. The version of Windows PowerShell that is required by the script does not match the currently running
version of Windows PowerShell 4.0.
At line:1 char:1
+ .\MyWebApp.ps1
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (MyWebApp.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion
PS> Import-Module .\MyWebApp.psm1
PS>
使用模块清单
正确验证需求的唯一方法是使用模块清单。不幸的是,这必须是文件旁边的单独psm1
文件。以下清单将实现#Requires
注释的目的:
MyWebApp.psd1
:
#
# Module manifest for module 'MyWebApp'
#
@{
ModuleVersion = '1.0'
PowerShellVersion = '4.0'
RequiredModules = @('WebAdministration')
RootModule = @('.\MyWebApp.psm1')
}
导入这个文件给出了我们想要的错误:
PS> Import-Module .\MyWebApp.psd1
Import-Module : The required module 'WebAdministration' is not loaded. Load the module or remove the module from 'RequiredModules' in the file
'.\MyWebApp.psd1'.
At line:1 char:1
+ Import-Module .\MyWebApp.psd1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (.\MyWebApp.psd1:String) [Import-Module], MissingMemberException
+ FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand
不幸的是,您不能在同一个文件中声明该函数。您必须使用单独 psd1
的文件,然后将原始psm1
脚本显式声明为“根模块”。根模块表示为相对于文件的路径。psd1
其他属性:
ModuleVersion
是必需的。它必须存在。
PowerShellVersion
达到#Requires -Version 4
目的。
RequiredModules
达到#Requires -Modules WebAdministration
目的。
请注意,在和文件Test-MyWebApp
中都隐式导出。这通常由文件控制;模块清单中的等价物是. 我发现从清单中省略并控制脚本中使用的导出内容更简单。psm1
psd1
Export-ModuleMember -Function
psm1
FunctionsToExport
FunctionsToExport
Export-ModuleMember
psm1