2009-11-26 97 views

回答

82

您可以像这样运行(但是这显示了窗口一会儿):

PowerShell.exe -windowstyle hidden { your script.. } 

或者您使用我创建的帮助程序文件来避免名为PsRun.exe的窗口完全执行此操作。你可以下载源文件和exe文件Run scheduled tasks with WinForm GUI in PowerShell。我将它用于计划任务。

编辑:正如Marco指出的那样-windowstyle参数仅适用于V2。

+1

不错的提示。我也需要它来完成预定的任务:) – 2009-11-26 10:32:36

+7

对于任何想要尝试此操作的人,您需要使用PowerShell v2来获取-WindowStyle参数。 – 2009-11-27 11:38:46

+3

我编译了PsRun,但是,如果我将它添加到计划任务中,它也会闪烁一个窗口... – Ciantic 2015-12-12 17:33:43

4

从c#运行时,在Windows 7上,运行隐藏的PowerShell窗口作为SYSTEM帐户时弹出“交互式服务检测”服务。

使用“CreateNoWindow”参数阻止了ISD服务弹出警告。

process.StartInfo = new ProcessStartInfo("powershell.exe", 
    String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand)) 
{ 
    WorkingDirectory = executablePath, 
    UseShellExecute = false, 
    CreateNoWindow = true 
}; 
9

这是一种不需要命令行参数或单独的启动程序的方法。它并不完全隐形,因为窗口在启动时会瞬间显示。但它很快就消失了。如果你想通过在资源管理器中双击或通过开始菜单快捷方式(当然包括启动子菜单)来启动脚本,那么这就是我认为的最简单的方法。我喜欢它是脚本本身的代码的一部分,而不是外部的东西。

将这个在脚本的前面:

$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' 
add-type -name win -member $t -namespace native 
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0) 
2

这里是一个班轮:

mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& 'C:\Example Path That Has Spaces\My Script.ps1'"""""", 0 : window.close") 

虽然有可能为这个闪烁的窗口很简单,这应该是一个罕见的发生。

1

我认为在运行后台脚本时隐藏PowerShell控制台屏幕的最佳方法是this code(“Bluecakes”answer)。

我在我需要在后台运行的所有PowerShell脚本的开头添加此代码。

# .Net methods for hiding/showing the console in the background 
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); 
' 
function Hide-Console 
{ 
    $consolePtr = [Console.Window]::GetConsoleWindow() 
    #0 hide 
    [Console.Window]::ShowWindow($consolePtr, 0) 
} 
Hide-Console 

如果这个答案是帮你,请投至"Bluecakes" in his answer in this post.

相关问题