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

mqkwyuun  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(156)

当我尝试在内存中加载程序时出现此错误
错误:

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)
gcuhipw9

gcuhipw91#

正如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入口点-可以在this answer中找到。

相关问题