【问题标题】:How to call a Win32 API Function from Powershell?如何从 Powershell 调用 Win32 API 函数?
【发布时间】:2020-12-15 00:50:51
【问题描述】:

我需要使用 PowerShell 从 Win 32 API 中的 Imagehlp.dll 调用 MapFileAndCheckSumA 函数。我曾尝试在网上遵循一些类似的教程,例如: https://devblogs.microsoft.com/scripting/use-powershell-to-interact-with-the-windows-api-part-1/ 我曾尝试使用 Add-Type cmdlet 在 PowerShell 中编译 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# 还很陌生,因此,我不知道如何进行这项工作。你能帮帮我吗?

【问题讨论】:

  • 您在使用CharSet.Auto 时需要导入MapFileAndCheckSum(没有A)。参数不应该是IntPtr,而是out int(或uint),然后在PowerShell中你可以使用[ref]传递参数。
  • 感谢您的快速回复。我已经尝试过您的解决方案,据我了解,函数运行后需要更改 ref 值。虽然函数输出 true,但 ref 值似乎没有改变。输出为:[ref]$xValue5

标签: c# .net powershell winapi


【解决方案1】:

所有的事情都错了:

  • 当使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2011-03-06
    • 2019-08-04
    • 1970-01-01
    • 2011-05-09
    相关资源
    最近更新 更多