这需要一些 .NET 互操作,如本博客中所述:
TechEd 2012 中的脚本…第 1 部分(将 PowerShell 窗口保持在顶部) https://blogs.msdn.microsoft.com/taylorb/2012/06/12/scripts-from-teched-2012-part-1-keeping-powershell-window-on-top/
我复制了下面的相关代码,以防链接网站消失:
$signature = @'
[DllImport("user32.dll")]
public static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
uint uFlags);
'@
$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru
$handle = (Get-Process -id $Global:PID).MainWindowHandle
$alwaysOnTop = New-Object -TypeName System.IntPtr -ArgumentList (-1)
$type::SetWindowPos($handle, $alwaysOnTop, 0, 0, 0, 0, 0x0003)
Edit:
如评论中所述:如果您来自批处理文件,PowerShell 在子进程中运行并且不拥有控制台窗口,因此您必须进行更改:
$signature = @'
[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
uint uFlags);
'@
$type = Add-Type -MemberDefinition $signature -Name SetWindowPosition -Namespace SetWindowPos -Using System.Text -PassThru
$handle = $type::GetConsoleWindow()
$type::SetWindowPos($handle, -1, 0, 0, 0, 0, 0x0003)