我正在尝试从脚本专家中实现此代码示例: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
代码:
$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行都以类似的错误结束。该错误消息对调试没有多大帮助。有没有办法获得有关错误的更多信息?
答案 0 :(得分:1)
有没有办法获得更多关于错误的信息?
您可能会尝试获取更多详细信息。首先,在catch块中,立即捕获 $ error [0] 和 $ _ 。这两个通常包含最新的错误信息,具体取决于您正在做什么。立即捕获它们将确保它们不会被捕获块中的某些东西覆盖。
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
强制进行更详细的说明。 Powershell Tips & Tricks post显示上述命令的输出结果。