无法设置通信对象值



我有一段代码打开一个单词模板,然后尝试设置命名FormFields的值。

$options = @{
    'foo' ='bar';
    'bizz' = 'buzz';
}
$document = 'C:Form_template.doc'
$word = new-object -ComObject Word.application
$doc = $word.Documents.Open($document)
$word.visible = $true
$fields = $doc.FormFields
$fields.item('foo').Result = $options['foo']
$fields.item('bizz').Result = $options['bizz']

运行此代码段时,表单字段设置不正确。但是,当我跑步时

$fields.item('foo').Result = 'bar'
$fields.item('bizz').Result = 'buzz'

这些值是根据需要设置的。

编辑:这是交互式外壳中的一个例子

PS C:>$fields.item('foo').Result = $options['foo']
PS C:>$fields.item('bizz').Result = $options['bizz']
PS C:> $doc.FormFields.Item('foo').Result
PS C:> $doc.FormFields.Item('bizz').Result
PS C:>#Now let's try setting the values directly with a string.
PS C:>$fields.item('foo').Result = 'bar'
PS C:>$fields.item('bizz').Result = 'buzz'
PS C:> $doc.FormFields.Item('foo').Result
bar
PS C:> $doc.FormFields.Item('bizz').Result
buzz

为什么我无法使用哈希中的值设置表单字段值?

根据 Ben 的建议,用 [string]$options['bizz'] 强制转换字符串导致正确设置值。

PS C:>$fields.item('bizz').Result = [string]$options['bizz']
PS C:> $doc.FormFields.Item('foo').Result
buzz

经过进一步调查,我发现将哈希值转换为字符串返回了不同的类型,而不是使用 .toString()

PS C:> $options['bizz'].getType()
IsPublic IsSerial Name                                     BaseType                                                         
-------- -------- ----                                     --------                                                         
True     True     String                                   System.Object                                                    
PS C:> $options['bizz'].toString().getType()
IsPublic IsSerial Name                                     BaseType                                                         
-------- -------- ----                                     --------                                                         
True     True     String                                   System.Object                                                    
PS C:> [string]$options['bizz'].getType()
string

我对为什么会这样感兴趣,但这将是另一个线程的主题。正确的铸造解决了我的问题。

最新更新