如何从Powershell调用GetStdHandle,GetConsoleMode?

时间:2016-06-27 02:53:46

标签: windows powershell pinvoke

尝试使用the Add-Type approach从Powershell脚本读取当前Windows控制台模式时出错:

$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)

但是我收到以下警告和错误:

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

知道我做错了吗?

更新:根据接受的答案,这里是更正后的代码:

$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)

1 个答案:

答案 0 :(得分:1)

尝试使用以下方法定义(我刚刚添加了公共访问修饰符)

$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);
'@