如何修复Powershell脚本,该脚本读取Assembly属性,但保留一个打开的文件句柄



当我在VS2013 C#PreBuildEvent块中运行以下脚本时,它会锁定我正在查询其属性的可执行文件/程序集:"打开文件句柄"是我得到的错误。当我以交互方式运行它时,它看起来工作得很好。如何添加"using"语句或关闭文件句柄?非常感谢。

函数Get-AssemblyProperty{参数($anExe="%temp%\my.exe",[ValidateSet('System.Runtime.Version.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.DebugableAttribute',"System.Runtime.CompilerServices.CompilationRelaxationsAttribute","System.Runtime.CompilerServices.RuntimeCompatibilityAttribute")]$anAttribute="System.Reflection.AssemblyDescriptionAttribute")$thisFcn="获取程序集属性"$assembly=[Reflection.assembly]::LoadFile($anexe)$ary=$assembly.GetCustomAttributesData()写入调试"$thisFcn:Array=$ary。"$row=$ary | Where Object{$_.AttributeType-类似于"$anAttribute"}写入调试"$thisFcn:Matching Row=$Row。"#匹配行=[System.Reflection.AssemblyDescriptionAttribute("我们对伟大公司的申请")]$ans=($row-split")[1]#秒写入调试"$thisFcn:Answer=$ans。"退货$ans}

从字节数组加载程序集,它不会锁定文件:

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

您尝试过"$assembly.Dispose()"吗?您可能想阅读此链接

最新更新