如何调试.psm1模块?
我在Module.psm1文件中定义了一些函数。
Script.ps1脚本导入它并调用这些函数。
这些函数不在Script.ps1中,因为我在使用ForEach-Object - Parallel。把公共函数放在Module.psm1中后,我可以在每个运行空间中再次导入它。
但如果在Module.psm1中出错,PowerShell只会给我这个:
ParserError: The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. Import-Module: \Module.ps1:114
那是调用import-module的那一行,而不是模块中的错误。
我得注释掉Module.psm1的部分代码来尝试定位问题。有没有更好的办法?
解决方案
你到处改了点东西,结果PowerShell告诉你无法解析,但只是给出你调用Import-Moduile的那一行。
你描述的是默认行为,可以通过修改 the $ErrorView 偏好变量 来覆盖:
PS ~> $ErrorView = [System.Management.Automation.ErrorView]::ConciseView # default behavior
PS ~> .\Script.ps1
ParserError: The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a
property.
Import-Module: C:\Users\IISResetMe\Script.ps1:1
Line |
1 | Import-Module .\Module.psm1
| ~~~~~~~~~~~~~~~~~~~~~~~~~
| The specified module '.\Module.psm1' was not loaded because no valid module file was found in any module directory.
现在让我们把 $ErrorView 设置为 DetailedView 试试看:
PS ~> $ErrorView = [System.Management.Automation.ErrorView]::DetailedView
PS ~> .\Script.ps1
Exception :
Type : System.Management.Automation.ParentContainsErrorRecordException
Message : At C:\Users\IISResetMe\Module.psm1:1 char:1
+ 123 = 456
+ ~~~
The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.
HResult : -2146233087
CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
FullyQualifiedErrorId : InvalidLeftHandSide
InvocationInfo :
ScriptLineNumber : 1
OffsetInLine : 1
HistoryId : -1
ScriptName : C:\Users\IISResetMe\Module.psm1
Line : 123 = 456
Statement : 123
PositionMessage : At C:\Users\IISResetMe\Module.psm1:1 char:1
+ 123 = 456
+ ~~~
PSScriptRoot : C:\Users\IISResetMe
PSCommandPath : C:\Users\IISResetMe\Module.psm1
CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, C:\Users\IISResetMe\Script.ps1: line 1
at <ScriptBlock>, <No file>: line 1
现在我们可以看到模块中真正导致解析错误的代码,不再需要猜测错误指的是哪条赋值语句。
如果 DetailedView 的设置过于冗长,试试 NormalView——它更简洁一些,但仍然会尽量显示抛出错误的调用点。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。