将控制台设置为PowerShell中的最顶部

将控制台设置为PowerShell中的最顶部,powershell,console,topmost,Powershell,Console,Topmost,因此,尽管有很多关于如何设置表单的建议,但我找不到任何可以使我的控制台运行到最顶层的东西 因此,我的问题是:如何使我的控制台在脚本运行期间运行得最好?这需要一些.NET互操作,如本博客中所述: 我已复制了以下相关代码,以防链接站点消失: $signature = @' [DllImport("user32.dll")] public static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter,

因此,尽管有很多关于如何设置表单的建议,但我找不到任何可以使我的控制台运行到最顶层的东西


因此,我的问题是:如何使我的控制台在脚本运行期间运行得最好?

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

我已复制了以下相关代码,以防链接站点消失:

$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)
编辑:

如注释中所述:如果您来自批处理文件,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)

@omgloyes:您可以将
$type::SetWindowPos($handle,$alwaysOnTop,0,0,0,0x0003)
替换为
$type::SetWindowPos($handle,-1,0,0,0,0x0003)
@boxdog,您的脚本在Powershell中有它。@omgloyes:如果您来自批处理文件,Powershell在子进程中运行,并且不拥有控制台窗口,因此,您必须进行更改:添加
[DllImport(“kernel32.dll”)]public static extern IntPtr GetConsoleWindow()
$signature
的值替换为
$handle=…
行,替换为
$handle=$type::GetConsoleWindow()
@RichMoss:最好避免使用非ASCII范围的引号,但请注意PowerShell本身完全支持它们。问题通常是字符编码的问题——请参阅。@RichMoss。正如我在文章中所说,我从博客上复制/粘贴了它,所以这就是奇怪的引用的来源。话虽如此,我还是应该检查一下,而不是仅仅假设它没问题。现在修复。看到这个和我的答案,你可以修改它做最上面的。很遗憾,我不能以管理员身份运行…:/