Forum Discussion
Hash/Array return values
I ran across a difference in return values for built in properties depending on whether collecting with a hash or an array. The code below selects an Excel document and iterates properties. If the $hash variable is set to $false the properties are collected as an array, otherwise as a hash. Script run in ISE for Powershell 5.1. A hash comes up with properties not included if array used. This is not a problem to be solved, per se, but is there an explanation for the difference.
$hash = $true #change to $false for array
$pop = New-Object -ComObject wscript.shell
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = $PSScriptRoot
Filter = 'Excel Files (*.xlsx;*.xls)|*.xlsx;*.xls'
Title = 'Select Excel File'
}
$result = $FileBrowser.ShowDialog()
If ($result -eq 'Cancel') {
$popup = $pop.popup("No File Selected",2,"Closing",4096)
exit
}
$xl = $FileBrowser.FileName
$popup = $pop.popup("Iterating Built In Properties for $xl `n Please Wait",4,"Running",4096)
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$workbook = $excel.Workbooks.Open($xl)
$binding = "System.Reflection.BindingFlags" -as [type]
if ($hash -eq $true) {$props = @{} }
else {$props = @() }
Foreach($property in $workbook.BuiltInDocumentProperties)
{
$pn = [System.__ComObject].invokemember("name",$binding::GetProperty,$null,$property,$null)
trap [system.exception]
{
if ($hash -eq $true) { $props.Add($pn,"Value Not Found")}
else {$props += "$pn`: Value Not Found"}
continue
}
if ($hash -eq $true) { $props.Add($pn,[System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null)) }
else {$props += "$pn`:" + [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$property,$null) }
}
$excel.quit()
$excel = $null
$props | FT
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Exit