在 PowerShell 中将控制台设置为最顶层

Omg*_*yes 5 console powershell topmost

因此,虽然有很多关于如何将表单设置为最顶层的建议,但我找不到任何使我的控制台在最顶层运行的东西。

所以我的问题是:如何让我的控制台在脚本期间运行在最上面?

box*_*dog 5

这需要一些 .NET 互操作,如本博客中所述:

\n\n

TechEd 2012\xe2\x80\xa6 第 1 部分中的脚本(将 PowerShell 窗口保持在顶部)

\n\n

我复制了下面的相关代码,以防链接网站消失:

\n\n
$signature = @\'\n[DllImport("user32.dll")]\npublic static extern bool SetWindowPos(\n    IntPtr hWnd,\n    IntPtr hWndInsertAfter,\n    int X,\n    int Y,\n    int cx,\n    int cy,\n    uint uFlags);\n\'@\n\n$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru\n\n$handle = (Get-Process -id $Global:PID).MainWindowHandle\n$alwaysOnTop = New-Object -TypeName System.IntPtr -ArgumentList (-1)\n$type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003)\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑:

\n\n

如评论中所述:如果您来自批处理文件,PowerShell 在子进程中运行并且不拥有控制台窗口,因此您必须进行更改:

\n\n
$signature = @\'\n[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();\n[DllImport("user32.dll")]\npublic static extern bool SetWindowPos(\n    IntPtr hWnd,\n    IntPtr hWndInsertAfter,\n    int X,\n    int Y,\n    int cx,\n    int cy,\n    uint uFlags);\n\'@\n\n$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru\n\n$handle = $type::GetConsoleWindow()\n$type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003)\n
Run Code Online (Sandbox Code Playgroud)\n

  • @boxdog,你的脚本有[大引号](https://practicaltypography.com/straight-and-curly-quotes.html),[没有得到很好的支持](https://4sysops.com/archives/dealing- Powershell 中的 with-smart-quotes-in-powershell/)。 (2认同)