简体   繁体   中英

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
}

Load the assembly from a byte array and it won't lock the file:

$bytes = [System.IO.File]::ReadAllBytes("C:\MyExe.exe")
[Reflection.Assembly]::Load($bytes)....

Have you tried to "$assembly.Dispose()"? You might want to read this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM