如何修复我的Powershell脚本,该脚本读取程序集属性但留下了打开的文件句柄?

问题描述:

当我从我的VS2013 C#PreBuildEvent块中运行下面的脚本时,它会锁定其查询属性的可执行文件/程序集:“打开文件句柄”是我得到的错误。 当我交互式运行它时,它似乎工作正常。 如何添加“使用”语句或以其他方式关闭文件句柄? 谢谢!如何修复我的Powershell脚本,该脚本读取程序集属性但留下了打开的文件句柄?

 
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 
} 
+1

一旦将程序集加载到应用程序域中,它就不能被卸载。您需要卸载整个应用程序域以释放它。 –

+1

请参阅[这里](http://stackoverflow.com/a/12807629/284111)了解变通方法。 –

你试过“$ assembly.Dispose()”吗? 您可能想要阅读this链接

+0

明天我会尝试第一件事! – AnneTheAgile

+0

“Assembly”对象没有'Dispose()'方法。 – Kev