thisguy123
thisguy123

Reputation: 945

Unable to set Comobject Value

I have a snippet of code that opens a word template, then attempts to set values of named 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']

When running this snippet, the form fields are not set properly. However, when I run

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

The values are set as desired.

Edit: Here's an example in Interactive shell

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

Why am I not able to set the FormField values using values from the hash?

Upvotes: 0

Views: 97

Answers (1)

thisguy123
thisguy123

Reputation: 945

Per a suggestion from Ben casting the string with [string]$options['bizz'] resulted in setting the value correctly.

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

Upon further investigation I found that casting the hash value to string returned a different type vs using .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

I'm interested in why that is, but that would be a topic for another thread. Proper casting resolved my issue.

Upvotes: 0

Related Questions