dimanche 22 novembre 2015

How can I fix my Powershell script which reads Assembly attributes but leaves an open file handle?

When I run the below script from within my VS2013 C# PreBuildEvent block, it locks the executable/assembly whose attributes I am querying: "open file handle" is the error I get. When I run it interactively, it appears to work fine. How can I add a 'using' statement or otherwise close the file handle? thank you!

function Get-AssemblyProperty  {
param
(
  $anExe       = "%temp%\my.exe",

  [ValidateSet('System.Runtime.Versioning.TargetFrameworkAttribute',
 'System.Reflection.AssemblyFileVersionAttribute',
 'System.Reflection.AssemblyTitleAttribute',
 'System.Reflection.AssemblyDescriptionAttribute',
 'System.Reflection.AssemblyConfigurationAttribute',
 'System.Reflection.AssemblyCompanyAttribute',
 'System.Reflection.AssemblyProductAttribute',
 'System.Reflection.AssemblyCopyrightAttribute',
 'System.Reflection.AssemblyTrademarkAttribute',
 'System.Runtime.InteropServices.ComVisibleAttribute',
 'System.Runtime.InteropServices.GuidAttribute',
 'System.Diagnostics.DebuggableAttribute',
 'System.Runtime.CompilerServices.CompilationRelaxationsAttribute',
 'System.Runtime.CompilerServices.RuntimeCompatibilityAttribute' )]
  $anAttribute = "System.Reflection.AssemblyDescriptionAttribute"

)
  $thisFcn = "Get-AssemblyProperties"
  $assembly = [Reflection.Assembly]::LoadFile($anexe)

  $ary = $assembly.GetCustomAttributesData()
  Write-Debug "$thisFcn : Array = $ary ."

  $row = $ary | Where-Object { $_.AttributeType -like "$anAttribute" }
  Write-Debug "$thisFcn : Matching Row = $row ."
  # Matching Row = [System.Reflection.AssemblyDescriptionAttribute("Our application for Great Company")]

  $ans = ( $row -split '"' )[1] # second
  Write-Debug "$thisFcn : Answer = $ans ."
  return $ans
}




Aucun commentaire:

Enregistrer un commentaire