Powershell 不一致的ComObject属性行为
我之前问了一个关于的问题,发现在设置ComObject属性值时出现了不规则行为Powershell 不一致的ComObject属性行为,powershell,com,Powershell,Com,我之前问了一个关于的问题,发现在设置ComObject属性值时出现了不规则行为 $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.
$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
我可以尝试用三种方式设置FormField的值,其行为与我预期的不同
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
编辑:
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
引擎盖下面发生了什么
除非我误解了什么,否则'bar'
对象和选项['foo']
对象是相同的类型,但它们在设置ComObject属性的值时会导致不同的行为
当我将字符串直接放入时,powershell是否会进行某种类型的类型推断?
[string]$options['foo'].getType()
是[string]($options['foo'].getType())
,而不是([string]$options['foo']).getType()
。显示此[type]:GetTypeArray((,$options['foo'])的输出。您是否尝试过$ErrorActionPreference=“Stop”
?如果是SilentlyContinue
则可能对您隐藏了原因。添加了额外的输出pet PetSerAl的问题Ben-这里没有发生错误,因此这不是问题。@Thisgy123您不发布此命令的输出:[type]::GetTypeArray(,$options['foo'])
-这是我最感兴趣的。@PetSerAl my bad,更新。