assembly 使用PowerShell从内存执行.NET应用程序

11dmarpk  于 2023-04-30  发布在  Shell
关注(0)|答案(1)|浏览(99)

你好,我有这个代码:

# Note: This must be an executable or DLL compiled for .NET
$Path = "C:\Users\sadettin\desktop\tok.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')))

代码的工作。NET框架控制台项目。不知何故,它不工作。NET框架窗体应用程序,我添加了这个:

$entryPointMethod.Invoke($null, $null)

目前,它可以在控制台和表单应用程序版本中工作。
但它不加载时,我试图把另一个。net程序到**$path我想这是因为$entryPointMethod**。所以我们需要修改它,使其适用于所有程序。
有没有一种方法可以使这个系统通用???如何做?谢谢

ctzwtxfj

ctzwtxfj1#

入口点不需要在Program类中(技术上甚至不需要称为Main,尽管这在C#中是强制的)。
获取入口点函数的正确方法是使用程序集的EntryPoint属性

# This example passes two arguments, 'foo' and 'bar'
$assembly.EntryPoint.Invoke($null, @('foo', 'bar'));

这只适用于可执行文件.exe。如果它是一个库.dll,那么它就没有入口点。

相关问题