如何从PowerShell调用Win32 API函数?

3

我需要在PowerShell中使用Win 32 API调用Imagehlp.dll中的MapFileAndCheckSumA函数。我已经尝试了一些类似的在线教程,例如这个链接: https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/ 我尝试使用Add-Type命令来编译C#代码。我写的代码如下:

Add-Type -TypeDefinition @"
 using System;
 using System.Diagnostics;
 using System.Runtime.InteropServices;

 public static class Imagehlp
 {
     [DllImport("imagehlp.dll", CharSet=CharSet.Auto)]
         public static extern bool MapFileAndCheckSumA(
             [MarshalAs(UnmanagedType.LPStr)] string Filename,
             UIntPtr HeaderSum,
             UIntPtr CheckSum);
 }
"@

 $x = [UIntPtr]::new(5)
 $y = [UIntPtr]::new(5)
 [Imagehlp]::MapFileAndCheckSumA("C:\Program Files\Internet Explorer\iexplore.exe", $x,$y)

然而,当我执行代码的最后一行时,我会收到以下异常。
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at Imagehlp.MapFileAndCheckSumA(String Filename, UIntPtr HeaderSum, UIntPtr CheckSum)
   at CallSite.Target(Closure , CallSite , Type , String , Object , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at System.Management.Automation.Interpreter.DynamicInstruction`5.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.DlrScriptCommandProcessor.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)
   at System.Management.Automation.DlrScriptCommandProcessor.Complete()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
   at System.Management.Automation.Runspaces.PipelineThread.WorkerProc()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

我在网上搜索了这个异常,猜测这是由代码中的C#部分引起的编译错误。网上的解决方案说我需要从我正在使用的IDE更改编译设置,但我对PowerShell和C#都比较新,因此我不知道如何使其工作。你能帮我吗?


你需要导入MapFileAndCheckSum(没有A)因为你使用了CharSet.Auto。参数应该不是IntPtr而是out int(或uint),然后在PowerShell中你可以使用[ref]来传递参数。 - undefined
非常感谢您的快速回复。我已经尝试了您的解决方案,据我所知,在函数运行后需要更改ref值。虽然函数输出为true,但是ref值似乎没有发生变化。输出结果为: [ref]$x 5 - undefined
1个回答

5

这段代码存在以下问题:

  • 当使用CharSet.Auto时,函数不应该同时有AW后缀,因为Auto将自动为您完成。
  • 当使用CharSet.Auto时,使用UnmanagedType.LPStr是错误的,因为它总是将字符串作为ANSI类型传递。
  • MapFileAndCheckSum文档中返回一个DWORD而不是BOOL。这一点尤其重要,因为成功的返回值是0,对应于False,而1("无法打开文件")对应于True
  • HeaderSumCheckSum是输出值的DWORD指针,应该以out int形式传递,而不是IntPtr

更正后的签名:

[DllImport("imagehlp.dll", CharSet = CharSet.Auto)]
public static extern int MapFileAndCheckSum(string Filename, out int HeaderSum, out int CheckSum); 

然后可以在PowerShell中按照以下方式调用:

[int] $headerSum = 0;
[int] $checkSum = 0;
$result = [Imagehlp]::MapFileAndCheckSum(
    "C:\Program Files\Internet Explorer\iexplore.exe", 
    [ref] $headerSum, 
    [ref] $checkSum
)

if ($result -ne 0) { 
    Write-Error "Error: $result" 
}
$headerSum, $checkSum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接