Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call GetStdHandle, GetConsoleMode from Powershell?

I'm getting error when trying to read the current Windows console mode from a Powershell script using the Add-Type approach:

$MethodDefinitions = @'
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
'@
$Kernel32 = Add-Type -MemberDefinition $MethodDefinitions -Name 'Kernel32' -Namespace 'Win32' -PassThru
$hConsoleHandle = $Kernel32::GetStdHandle(-11) # STD_OUTPUT_HANDLE 
$lpMode = 0
$Kernel32::GetConsoleMode($hConsoleHandle, $lpMode)

But I get the following warning and errors:

WARNING: The generated type defines no public methods or properties.
Method invocation failed because [Win32.Kernel32] does not contain a method named 'GetStdHandle'.
At C:\Users\John\get_console_mode.ps1:8 char:1
+ $hConsoleHandle = $Kernel32::GetStdHandle(-11) # STD_OUTPUT_HANDLE
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Method invocation failed because [Win32.Kernel32] does not contain a method named 'GetConsoleMode'.
At C:\Users\John\get_console_mode.ps1:10 char:1
+ $Kernel32::GetConsoleMode($hConsoleHandle, $lpMode)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Any idea what I'm doing wrong?

UPDATE: As per the accepted answer, here is the corrected code:

$MethodDefinitions = @'
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
'@
$Kernel32 = Add-Type -MemberDefinition $MethodDefinitions -Name 'Kernel32' -Namespace 'Win32' -PassThru
$hConsoleHandle = $Kernel32::GetStdHandle(-11) # STD_OUTPUT_HANDLE 
$mode = 0
$Kernel32::GetConsoleMode($hConsoleHandle, [ref]$mode)
like image 553
jwfearn Avatar asked Jun 27 '16 02:06

jwfearn


1 Answers

Try it with the following method definitions (I just added the public access modifier)

$MethodDefinitions = @'
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
'@
like image 97
DAXaholic Avatar answered Oct 25 '22 07:10

DAXaholic