Ironman Software Forums
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
In this blog post, we’ll use the
PInvoke module to call native methods in PowerShell.
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);
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.
PInvoke module includes and loads all the P\Invoke assemblies to provide access to all the native methods from PowerShell.
You can install the
PInvoke module from the PowerShell Gallery.
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)
Find this useful? Please consider sharing this article. Have a question about PowerShell? Contact us and we'll write a post about it.