如何在自我提升的Powershell脚本中隐藏控制台但不隐藏图形用户界面
如何在自我提升的Powershell脚本中隐藏控制台但不隐藏图形用户界面
我想为我的PowerShell脚本制作一个GUI,这样其他人也可以轻松使用它们。
我有一个主菜单脚本,它调用了一些其他脚本。
其中一个脚本需要一个提升的PowerShell进程。
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSFilePath`"" -Verb RunAs; exit }
现在我的问题是,不仅显示了$PSFilePath的GUI,还显示了一个空的控制台窗口。
我尝试使用了 -WindowStyle Hidden
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSFilePath`"" -WindowStyle Hidden -Verb RunAs; exit }
但结果是控制台和GUI都被隐藏了。
有没有办法只隐藏控制台窗口而不隐藏GUI?
如何在自我提权的PowerShell脚本中隐藏控制台但不隐藏GUI
有时候我们需要在PowerShell脚本中隐藏控制台窗口,但保持GUI窗口可见。这篇文章将介绍如何实现这一目标。
首先,我们需要添加以下代码到脚本中,以隐藏控制台窗口:
# Hide PowerShell Console Add-Type -Name Window -Namespace Console -MemberDefinition ' [DllImport("Kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow); ' $consolePtr = [Console.Window]::GetConsoleWindow() [Console.Window]::ShowWindow($consolePtr, 0)
以上代码使用C#的互操作性功能,通过调用相关的Windows API函数来隐藏控制台窗口。
然而,有人指出这篇文章的内容可能是重复的,因为已经有人在Stack Overflow上提出了类似的问题,并给出了解决方法。你可以在这里找到相关问题的链接:Opening PowerShell Script and hide Command Prompt, but not the GUI。
在Stack Overflow的解决方案中,通过将`[Console.Window]::ShowWindow($consolePtr, 0)`中的参数`0`更改为`2`,可以将控制台窗口最小化而不是隐藏。你可以在这里找到相关解决方案的链接:stackoverflow.com/a/40621143/1486850。
通过以上方法,我们可以在自我提权的PowerShell脚本中隐藏控制台窗口,同时保持GUI窗口可见。这对于需要在后台运行脚本但又需要显示GUI界面的情况非常有用。
在编写PowerShell脚本时,有时候希望隐藏控制台窗口但保留图形用户界面(GUI)。这个问题的出现原因是PowerShell脚本默认会打开一个控制台窗口,但是在某些情况下,我们希望将控制台窗口隐藏起来。
为了解决这个问题,我们可以在脚本的开头添加以下代码:
$dllvar = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' add-type -name win -member $dllvar -namespace native [native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
上述代码使用了`user32.dll`中的`ShowWindow`函数,该函数可以隐藏或显示指定窗口。在这里,我们将其应用于当前PowerShell进程的主窗口句柄,并将状态参数设置为0,即隐藏窗口。
通过在脚本开头添加上述代码,我们可以实现在执行脚本时隐藏控制台窗口,但仍保留图形用户界面的效果。这对于需要在后台运行的脚本或希望隐藏控制台窗口的脚本非常有用。