Saturday, December 29, 2012

List All Win32/Native Functions Declared/Used By PowerShell

The PowerShell v3 command below will list every P/Invoke declaration made by the assemblies loaded in your PowerShell session. This knowledge may be useful for those seeking to avoid performing their own P/Invoke declarations in PowerShell scripts. What does this mean for those unfamiliar with P/Invoke? This means that you can call the Win32/Native functions listed without needing to compile code (via Add-Type) or getting fancy with reflection.
What you may notice in the resultant output is Microsoft's inconsistency in declaring their DllImport attributes. For example, some dll names are all upper case, some are all lower case, some are camel case, and others lack the dll file extension. Lastly, it's worth noting that the same techniques used to dump the information from all loaded assemblies can be used on all assemblies in the GAC.

Here's the output of the command above from my PowerShell v3 session:

3 comments:

  1. Hi, could you please give an example howto call all these methods without compiling? I don't get it
    For example with kernel32.dll GetSystemInfo method ...

    ReplyDelete
    Replies
    1. Sure. Here's an example although GetSystemInfo is a bad example since it accepts a non-public structure as an argument.

      $Win32Native = [IntPtr].Assembly.GetType('Microsoft.Win32.Win32Native')
      $SystemInfoClass = $Win32Native.GetNestedType('SYSTEM_INFO', [Reflection.BindingFlags] 'NonPublic, Static')
      $SystemInfoClassRefType = $Win32Native.GetNestedType('SYSTEM_INFO', [Reflection.BindingFlags] 'NonPublic, Static').MakeByRefType()
      $GetSystemInfo = $Win32Native.GetMethod('GetSystemInfo', [Reflection.BindingFlags] 'NonPublic, Static')

      $SystemInfo = [Activator]::CreateInstance($SystemInfoClass)
      $GetSystemInfo.Invoke($null, @($SystemInfo))

      I wrote a series of blog posts on how to interact with the Win32 API in PowerShell. For GetSystemInfo, I would go the reflection route.

      Delete
    2. Here's the link to the posts: http://blogs.technet.com/b/heyscriptingguy/archive/2013/06/26/use-powershell-to-interact-with-windows-apis-part-2.aspx

      Delete