如何在自我提升的powershell脚本中隐藏控制台但不是GUI



我想为我的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隐藏

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?

尝试...

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

,但您的帖子是潜在的重复。

打开powershell脚本和hide命令提示,而不是gui

我很久以前找到了一个解决方案,它被埋在这里的某个地方,在stackoverflow上,但现在找不到指向它的链接。它将打开并立即关闭空控制台窗口。

只是将其粘贴到脚本的开头:

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

最新更新