Inconsistent ComObject property behavior

2019-09-12 11:59发布

问题:

I previously asked a question about setting ComObject property values, and found irregular behavior when setting ComObject property values.

$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

I can attempt to set the value of the FormField in three ways, and the behavior is different than I would anticipate.

PS C:\>#Attempting to set the property directly from the hash object returns failure.
PS C:\>$fields.item('foo').Result = $options['foo']
PS C:\> $doc.FormFields.Item('foo').Result

PS C:\> $options['foo'].getType()
IsPublic IsSerial Name                                     BaseType                                                         
-------- -------- ----                                     --------                                                         
True     True     String                                   System.Object 
PS C:\>#We can successfully set the value with a string directly.
PS C:\>$fields.item('foo').Result = 'bar'     
PS C:\> $doc.FormFields.Item('foo').Result
bar
PS C:\>#But this object is the same type as the hash object...
PS C:\>'bar'.getType()
IsPublic IsSerial Name                                     BaseType                                                         
-------- -------- ----                                     --------                                                         
True     True     String                                   System.Object 
PS C:\>#If we set the value with a [string] cast, we also get success
PS C:\>$fields.item('foo').Result = [string]$options['foo']
PS C:\>$doc.FormFields.Item('foo').Result
buzz
PS C:\>#But this object is a different type.
PS C:\> [string]$options['foo'].getType()
string

Edit:

PS C:\Users\stobias> ([string]$options['foo']).getType()
IsPublic IsSerial Name                                     BaseType                                                         
-------- -------- ----                                     --------                                                         
True     True     String 
PS C:\Users\stobias\Desktop> [type]::GetTypeArray((,$options['CommonName']))

IsPublic IsSerial Name                                     BaseType                                                       
-------- -------- ----                                     --------                                                       
True     True     String                                   System.Object   

So what's going on under the hood here?

Unless I'm misunderstanding something, the 'bar' object and the options['foo'] object are the same type, but they result in different behavior when setting the value of the ComObject property.

Is there some type of type inference that powershell does when I put a string directly in?