2 # Usage: powershell <path>\IdentifyConsoleWindow.ps1
4 # This script determines whether the process has a console attached, whether
5 # that console has a non-NULL window (e.g. HWND), and whether the window is on
6 # the current window station.
10 [DllImport("kernel32.dll", SetLastError=true)]
11 public static extern IntPtr GetConsoleWindow();
13 [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
14 public static extern bool SetConsoleTitle(String title);
16 [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
17 public static extern int GetWindowText(IntPtr hWnd,
18 System.Text.StringBuilder lpString,
22 $WinAPI = Add-Type -MemberDefinition $signature `
23 -Name WinAPI -Namespace IdentifyConsoleWindow -PassThru
25 if (!$WinAPI::SetConsoleTitle("ConsoleWindowScript")) {
26 echo "error: could not change console title -- is a console attached?"
29 echo "note: successfully set console title to ""ConsoleWindowScript""."
32 $hwnd = $WinAPI::GetConsoleWindow()
34 echo "note: GetConsoleWindow returned NULL."
36 echo "note: GetConsoleWindow returned 0x$($hwnd.ToString("X"))."
37 $sb = New-Object System.Text.StringBuilder -ArgumentList 4096
38 if ($WinAPI::GetWindowText($hwnd, $sb, $sb.Capacity)) {
39 $title = $sb.ToString()
40 echo "note: GetWindowText returned ""${title}""."
41 if ($title -eq "ConsoleWindowScript") {
44 echo "error: expected to see ""ConsoleWindowScript""."
45 echo " (Perhaps the console window is on a different window station?)"
48 echo "error: GetWindowText could not read the window title."
49 echo " (Perhaps the console window is on a different window station?)"