Add-Type - 处理具有struct参数的函数

时间:2015-08-26 05:47:29

标签: powershell

我尝试将函数导入PowerShell,并将Struct作为参数。我找不到"类型未找到"错误,但我不确定如何包含它。任何帮助将不胜感激。

  $MethodDefinition = (
'[DllImport("kernel32.dll")]static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);')

$Kernel32 = Add-Type -MemberDefinition $MethodDefinition -Name 'Kernel32' -Namespace 'Win32' -PassThru

==== EDIT ====

所以这段代码加载了函数:

$MethodDefinition =
@'

public struct MEMORY_BASIC_INFORMATION
{
    public IntPtr BaseAddress;
    public IntPtr AllocationBase;
    public uint AllocationProtect;
    public uint RegionSize;
    public uint State;
    public uint Protect;
    public uint Type;
}

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]public static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, byte[] lpBuffer, int     dwSize, ref int lpNumberOfBytesRead);
[DllImport("kernel32.dll")]static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
'@

$Kernel32 = Add-Type -MemberDefinition $MethodDefinition -Name 'Kernel32' -Namespace 'Win32' -PassThru

但是我在尝试访问该功能时遇到错误。

代码:

$bMem = $Kernel32[1] #the structure, found that $Kernel32 is now an array
[Win32.Kernel32]::VirtualQueryEx($handle, 0, [ref] $bMem, 28);

错误:

 Method invocation failed because [Win32.Kernel32] doesn't contain a method named 'VirtualQueryEx'.

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

如果我执行此操作,它会告诉我您错过了MEMORY_BASIC_INFORMATION的声明:

free()

所以试试这个:

The type or namespace name 'MEMORY_BASIC_INFORMATION' could not be found (are you missing a using directive or an 
assembly reference?)