2009-11-26 188 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.

相關問題