Platform Invoke in PowerShell

Image Description

Daily PowerShell #62

Daily PowerShell Windows dotnet

December 21, 2021

quote Discuss this Article

In this blog post, we’ll use the PInvoke module to call native methods in PowerShell.

What is Platform Invoke (P\Invoke)?

Platform Invoke, often shortened to P\Invoke, is the method for calling native functions from .NET. It allows for creating signatures in a managed way for invoking non-managed functions. They typically require a compiled class and are notoriously hard to create correctly.

For example, the Windows User32 API contains a function called MessageBox. It’s used for display standard Windows message boxes to users. The signature looks like this.

int MessageBox(
  [in, optional] HWND    hWnd,
  [in, optional] LPCTSTR lpText,
  [in, optional] LPCTSTR lpCaption,
  [in]           UINT    uType
);

In C#, you would the define a P\Invoke signature to call this API. It specifies the DLL the API resides in and a managed signature to use to call the API.

// Import user32.dll (containing the function we need) and define
// the method corresponding to the native function.
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);

You could then use the method call within your C# application. Note, you can use P\Invoke for calling any native exported function; not just Windows APIs.

MessageBox(IntPtr.Zero, "Command-line message box", "Attention!", 0);

What are the PInvoke NuGet packages?

Microsoft has developed a method of generating P\Invoke signatures and now publishes NuGet packages that contain the proper signatures for all the exposed APIs in Windows.

Calling P\Invoke from PowerShell

The PInvoke module includes and loads all the P\Invoke assemblies to provide access to all the native methods from PowerShell.

Install the PInvoke Module

You can install the PInvoke module from the PowerShell Gallery.

Install-Module PInvoke

Call Native Methods from PowerShell

To call a native method from PowerShell, you can reference the proper PInvoke class and call the method directly.

[PInvoke.Kernel32]::LoadLibrary('native.dll')
[PInvoke.User32]::MessageBox(0, 'Hello', 'Hello', 0)