如何运行PowerShell脚本而不向用户显示窗口或任何其他符号?

换句话说,脚本应该在后台安静地运行,而不需要向用户发出任何信号。

不使用第三方组件的答案可获得额外分数:)


当前回答

我认为在运行后台脚本时隐藏PowerShell控制台屏幕的最好方法是这个代码(“Bluecakes”答案)。

我将这段代码添加到需要在后台运行的所有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

如果这个答案是帮助你,请在这篇文章中投票给“蓝蛋糕”。

其他回答

您可以使用PowerShell社区扩展来完成以下操作:

start-process PowerShell.exe -arg $pwd\foo.ps1 -WindowStyle Hidden

你也可以用VBScript: http://blog.sapien.com/index.php/2006/12/26/more-fun-with-scheduled-powershell/这样做

计划隐藏的PowerShell任务(Internet Archive) 更多的乐趣与计划的PowerShell(互联网档案)

(通过这个论坛。)

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

把这个放在你的脚本前面:

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

我认为在运行后台脚本时隐藏PowerShell控制台屏幕的最好方法是这个代码(“Bluecakes”答案)。

我将这段代码添加到需要在后台运行的所有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

如果这个答案是帮助你,请在这篇文章中投票给“蓝蛋糕”。

我从c#运行时遇到了这个问题,在Windows 7上,“交互式服务检测”服务在以SYSTEM帐户运行隐藏的powershell窗口时弹出。

使用"CreateNoWindow"参数可以防止ISD服务弹出警告。

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

你可以像这样运行它(但这会显示一个窗口):

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

或者您可以使用我创建的一个帮助文件来避免名为PsRun.exe的窗口,它正是这样做的。您可以在PowerShell中使用WinForm GUI运行计划任务中下载源文件和exe文件。我用它来完成计划好的任务。

已编辑:正如Marco所指出的,此-WindowStyle参数仅适用于V2及以上版本。