Accessing API Functions and Logging Off

by Dec 7, 2015

You may have heard about pInvoke.net, a site that documents internal Windows API signatures. Signatures describe low-level Windows API system calls.

Here is an example of such a definition for the ShutdownWindowsEx API function:

$signature = @'
[DllImport("user32.dll")] 
public static extern int ExitWindowsEx(int uFlags, int dwReason); 
'@

To run this system function from inside your PowerShell scripts, read in the signature using Add-Type. Add-Type expects a namespace and a name. These two parts become the type name, and you can later use them to access the function.

#requires -Version 2


$signature = @'
[DllImport("user32.dll")] 
public static extern int ExitWindowsEx(int uFlags, int dwReason); 
'@

Add-Type -MemberDefinition $signature -Namespace Win32 -Name APIExample

[Win32.APIExample]::ExitWindowsEx(0, 0)

Of course you would still need to know how to operate ShutdownWindowsEx, and what the uFlags and dwReason parameters stand for. When you specify 0 for both, Windows tries to log off but gives the user a chance to save unsaved work. When you specify 10 for uFlags, you get a forced logoff.

Twitter This Tip! ReTweet this Tip!