簡體   English   中英

如何修復我的Powershell腳本,該腳本讀取Assembly屬性但留下打開的文件句柄?

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

當我從VS2013 C#PreBuildEvent塊中運行以下腳本時,它鎖定了我要查詢其屬性的可執行文件/程序集:“打開文件句柄”是我得到的錯誤。 當我以交互方式運行它時,它似乎可以正常工作。 如何添加“ using”語句或關閉文件句柄? 謝謝!

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
}

從字節數組加載程序集,它將不會鎖定文件:

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

您是否嘗試過“ $ assembly.Dispose()”? 您可能需要閱讀鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM