PowerShell:无法写入 CustomDocumentProperties / GetType 返回 null

问题描述 投票:0回答:1

我正在尝试通过 powershell 脚本编写 .docx word 文档的自定义文档属性。

显然不能通过简单地访问MSDN文档中描述的属性来完成,而是必须通过反射来调用它们,就像脚本编写人员herehere所描述的那样。 (有谁知道这是为什么吗?)

按照代码示例,我能够将文档属性打印到 shell 输出。

在执行应该编写它们的代码时,在尝试获取 CustomDocumentProperties 属性的类型时收到 NullReferenceException。

这是一个最小的例子:

$file = "c:\Temp\Test.docx"

$word = New-Object -ComObject Word.Application

$word.Visible = $false

$doc = $word.Documents.Open($file)

$customProperties = $doc.CustomDocumentProperties
Write-Host $customProperties # returns System.__ComObject [...] System.__ComObject, so it can't be null
$customProperties.GetType() # this line throws 'Object reference not set to an instance of an object.'

$doc.Close()
$word.Quit()

GetType()
怎么可能返回null?

我觉得我被困住了,好像我错过了一些东西......任何帮助将不胜感激。

powershell interop
1个回答
0
投票

注意:这篇文章不是解决方案,但提供了一些背景信息

$doc.CustomDocumentProperties
不是
.NET
意义上的 $null - 它仍然是 COM 对象的运行时可调用包装器 (RCW) - 但实际上代表一个 null 值,即缺少COM 对象/类实例。

您可以通过使用内在

pstypenames
属性来报告给定实例的类型名称(继承链)来验证这一点:

$doc.CustomDocumentProperties.pstypenames

输出:

System.__ComObject#{00000000-0000-0000-0000-000000000000}
System.__ComObject
System.MarshalByRefObject
System.Object

System.__ComObject
告诉您正在处理 COM 对象引用,而
{00000000-0000-0000-0000-000000000000}
告诉您此对象引用指向 没有对象,因此会出现
Object reference not set to an instance of an object.
错误消息。


将此与尝试在真正的 .NET

$null
值上调用方法进行对比:

$null.Foo()

输出:

InvalidOperation: You cannot call a method on a null-valued expression.

现在至于为什么

$doc.CustomDocumentProperties
没有指向实际的对象以及如何补救,我不知道 - 如果有人知道,请告诉我们。

© www.soinside.com 2019 - 2024. All rights reserved.