如何调试PowerShell的异常调用“InvokeMember”和“5”的说法(S):类型不匹配
我试图实现从脚本专家此代码示例:http://blogs.technet.com/b/heyscriptingguy/archive/2010/04/06/hey-scripting-guy-how-can-i-add-custom-properties-to-a-microsoft-word-document.aspx如何调试PowerShell的异常调用“InvokeMember”和“5”的说法(S):类型不匹配
代码:
$path = "C:\fso\Test.docx"
$application = New-Object -ComObject word.application
$application.Visible = $false
$document = $application.documents.open($path)
$binding = "System.Reflection.BindingFlags" -as [type]
$customProperties = $document.CustomDocumentProperties
$typeCustomProperties = $customProperties.GetType()
$CustomProperty = "Client"
$Value = "My_WayCool_Client"
[array]$arrayArgs = $CustomProperty,$false, 4, $Value
Try
{
$typeCustomProperties.InvokeMember(`
"add", $binding::InvokeMethod,$null,$customProperties,$arrayArgs) |
out-null
}
Catch [system.exception]
{
$propertyObject = $typeCustomProperties.InvokeMember(`
"Item", $binding::GetProperty,$null,$customProperties,$CustomProperty)
$typeCustomProperties.InvokeMember(`
"Delete", $binding::InvokeMethod,$null,$propertyObject,$null)
$typeCustomProperties.InvokeMember(`
"add", $binding::InvokeMethod,$null,$customProperties,$arrayArgs) |
Out-Null
}
$document.Saved = $false
$document.save()
$application.quit()
$application = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
错误(我删除的try-catch包装,其目的是处理这种情况时要添加的自定义属性已存在的docx文件,它没有):
Exception calling "InvokeMember" with "5" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At C:\Set-WordCustomProperties.ps1:16 char:3
所有不同的InvokeMethod行都以类似的错误结束。该错误消息对调试不是很有帮助。有什么方法可以获得有关错误的更多信息吗?
有没有什么办法可以获得更多不正确的信息?
有几件事你可能会尝试获得更详细的信息。首先,在您的catch块中,立即捕获$ error [0]和$ _。这两个通常包含最新的错误信息取决于你在做什么。立即捕获它们将确保它们不被catch块中的某些东西覆盖。
Catch [system.exception]
{
$err1 = $error[0]
$err2 = $_
$propertyObject = $typeCustomProperties.InvokeMember(`
"Item", $binding::GetProperty,$null,$customProperties,$CustomProperty)
$typeCustomProperties.InvokeMember(`
"Delete", $binding::InvokeMethod,$null,$propertyObject,$null)
$typeCustomProperties.InvokeMember(`
"add", $binding::InvokeMethod,$null,$customProperties,$arrayArgs) |
Out-Null
}
或者,你可以使用...
$error[0]|format-list –force
要强制进行更详细的解释。 A Powershell Tips & Tricks post显示了上述命令的输出结果。
很感谢。我不明白为什么这个问题会得到冷落,我没有时间立即跟进这些建议,但我希望尽快得到这个结果。 – gakera
您是否试过'$ document.CustomerProperties.Add($ CustomProperty,$ false,4,$ Value)'? –
不,我可能会尝试,但我怀疑它会起作用,那代码中的所有Com对象舞蹈都会发生什么......我认为这是必需的。 – gakera