如何从本地PowerShell模块导出/导入Cmdlet?导出异常排查
PowerShell模块Cmdlet导出导入问题排查
问题描述
自定义模块中的Write-Debug无法成功导出和导入,调用时无法输出预期的Verbose信息。
模块代码(.\Modules\Tools.psm1)
Function Write-Message() { param ([String] $Message) Write-Information -InformationAction Continue $Message } function Write-Debug() { [CmdletBinding()] param ([String] $Message) Write-Verbose $Message } Export-ModuleMember ` -Function Write-Message ` -Cmdlet Write-Debug
预期调用脚本(.\Main.ps1)
[CmdletBinding()] param() Import-Module $PSScriptRoot\Modules\Tools.psm1 Write-Debug "is just a test" Write-Message "hello world!"
实际执行结果
pwsh -file .\main.ps1 -Verbose VERBOSE: Loading module from path 'C:\dev\snippets\powershell\modules\Modules\Tools.psm1'. VERBOSE: Exporting function 'Write-Message'. VERBOSE: Importing function 'Write-Message'. hello world!
期望效果
- 成功导出并导入自定义的
Write-Debug(作为支持通用参数的高级函数) - 输出Verbose信息:
is just a test
错误原因与解决方法
核心错误点
错误使用
-Cmdlet参数导出高级函数Export-ModuleMember的-Cmdlet参数仅适用于编译型Cmdlet(比如用C#编写的二进制Cmdlet),而你定义的Write-Debug是带[CmdletBinding()]的PowerShell高级函数,属于函数范畴,必须用-Function参数导出。之前的写法会导致PowerShell忽略Write-Debug的导出请求,所以该函数根本没被导入到调用脚本中,执行时实际调用的是系统内置的Write-Debug(默认不输出内容)。Verbose参数未正确传递
即使函数被正确导出,调用时如果没有显式传递-Verbose开关,高级函数内部的Write-Verbose不会输出内容(默认$VerbosePreference为SilentlyContinue)。
修改方案
1. 修正模块的导出逻辑
修改Tools.psm1中的Export-ModuleMember部分,将-Cmdlet Write-Debug替换为-Function Write-Debug:
Function Write-Message() { param ([String] $Message) Write-Information -InformationAction Continue $Message } function Write-Debug() { [CmdletBinding()] param ([String] $Message) Write-Verbose $Message } Export-ModuleMember ` -Function Write-Message, Write-Debug
2. 修正调用脚本的参数传递
在Main.ps1中,调用Write-Debug时显式添加-Verbose开关,或者继承脚本的Verbose参数状态:
[CmdletBinding()] param() Import-Module $PSScriptRoot\Modules\Tools.psm1 # 方式1:显式传递Verbose开关 Write-Debug "is just a test" -Verbose # 方式2:继承脚本的Verbose参数(如果脚本调用时加了-Verbose则生效) # Write-Debug "is just a test" -Verbose:$($PSCmdlet.MyInvocation.BoundParameters['Verbose'].IsPresent) Write-Message "hello world!"
修改后的执行结果
运行命令pwsh -file .\main.ps1 -Verbose会得到如下输出:
VERBOSE: Loading module from path 'C:\dev\snippets\powershell\modules\Modules\Tools.psm1'. VERBOSE: Exporting function 'Write-Message'. VERBOSE: Exporting function 'Write-Debug'. VERBOSE: Importing function 'Write-Message'. VERBOSE: Importing function 'Write-Debug'. VERBOSE: is just a test hello world!
内容的提问来源于stack exchange,提问作者Thomas Lehmann
相关产品推荐
相关产品推荐

