Skip to content

Instantly share code, notes, and snippets.

@michaelvdnest
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save michaelvdnest/8c307bb1a9c6e3a2acae to your computer and use it in GitHub Desktop.

Select an option

Save michaelvdnest/8c307bb1a9c6e3a2acae to your computer and use it in GitHub Desktop.
Gets the windows together with process id that are open on the local computer
. '\Logging_Functions.ps1'
Function Get-Windows{
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)][string]$LogFile
)
Write-Verbose 'Performing operation "Get-Windows"'
if ($LogFile) {
Log-Write -LogPath $sLogFile -LineValue 'Performing operation "Get-Windows"'
}
Add-Type @"
public class Windows
{
private System.Collections.Generic.List<Window> windows;
public System.Collections.Generic.List<Window> GetWindows() {
windows = new System.Collections.Generic.List<Window>();
// instantiate the delegate
WindowEnumDelegate del = new WindowEnumDelegate(WindowEnumProc);
// call the win32 function
EnumChildWindows(System.IntPtr.Zero, del, 0);
return windows;
}
// declare the delegate
public delegate bool WindowEnumDelegate (System.IntPtr hwnd, int lParam);
// declare the API function to enumerate child windows
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int EnumChildWindows(System.IntPtr hwnd, WindowEnumDelegate del, int lParam);
// declare the GetWindowText API function
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetWindowText(System.IntPtr hwnd, System.Text.StringBuilder bld, int size);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(System.IntPtr hWnd, out uint lpdwProcessId);
public bool WindowEnumProc(System.IntPtr hwnd, int lParam) {
// get the text from the window
System.Text.StringBuilder bld = new System.Text.StringBuilder(256);
GetWindowText(hwnd, bld, 256);
string text = bld.ToString();
uint lpdwProcessId;
GetWindowThreadProcessId(hwnd, out lpdwProcessId);
if(text.Length > 0) {
Window window = new Window();
window.WindowText = text;
window.ProcessId = lpdwProcessId;
windows.Add(window);
}
return true;
}
}
public class Window {
public string WindowText;
public uint ProcessId;
}
"@
$object = New-Object Windows
$windows = $object.GetWindows()
Write-Verbose "Windows count: $($windows.Count)"
if ($LogFile) {
Log-Write -LogPath $LogFile -LineValue "Windows count: $($windows.Count)"
}
$windows
}
#Get-Windows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment