从字节数组加载.NET程序集



当我试图在内存中加载程序时,我遇到了这个错误

错误:

GAC    Version        Location
---    -------        --------
False  v2.0.50727

这是我的代码:

$Path = "D:calc.exe"
$bytes = [System.IO.File]::ReadAllBytes($Path)
$string = [System.Convert]::ToBase64String($bytes)
$bytees = [System.Convert]::FromBase64String($string)
[System.Reflection.Assembly]::Load($bytees)

正如Maximilian Burszley所指出的,您看到的是而不是错误

事实上,这表明您的程序集已成功从字节数组加载

System.Reflection.Assembly.Load方法返回一个代表加载的程序集的System.Reflection.Assembly实例,由于您没有将该返回值分配给变量,PowerShell将对象的友好表示隐式打印到控制台,这就是您所看到的;如果将| Format-List附加到[System.Reflection.Assembly]::Load($bytees)调用,您将看到有关新加载的程序集的更详细信息。

程序集中定义的任何公共类型现在都应该在PowerShell会话中可用;但是,假设您将*.exe文件指示为源文件,也许您希望像执行原始可执行文件一样执行程序集,可能需要使用命令行参数

提供完整的示例:

# Note: This must be an executable or DLL compiled for .NET
$Path = "D:calc.exe"
# Get Base64-encoded representation of the bytes that make up the assembly.
$bytes = [System.IO.File]::ReadAllBytes($Path)
$string = [System.Convert]::ToBase64String($bytes)
# ...
# Convert the Base64-encoded string back to a byte array, load
# the byte array as an assembly, and save the object representing the
# loaded assembly for later use.
$bytes = [System.Convert]::FromBase64String($string)
$assembly = [System.Reflection.Assembly]::Load($bytes)

# Get the static method that is the executable's entry point.
# Note: 
#   * Assumes 'Program' as the class name, 
#     and a static method named 'Main' as the entry point.
#   * Should there be several classes by that name, the *first* 
#     - public or non-public - type returned is used.
#     If you know the desired type's namespace, use, e.g.
#     $assembly.GetType('MyNameSpace.Program').GetMethod(...)
$entryPointMethod = 
$assembly.GetTypes().Where({ $_.Name -eq 'Program' }, 'First').
GetMethod('Main', [Reflection.BindingFlags] 'Static, Public, NonPublic')
# Now you can call the entry point.
# This example passes two arguments, 'foo' and 'bar'
$entryPointMethod.Invoke($null, (, [string[]] ('foo', 'bar')))

注意:在这个答案中可以找到上述的泛化,它不需要您知道名称,并且调用CLI入口点而不需要参数

相关内容

最新更新