如何才能运行一个 电源外壳 脚本而不向用户显示窗口或任何其他标志?

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

不使用第三方组件的答案需额外加分:)

有帮助吗?

解决方案

您可以像这样运行它(但这会显示一段时间的窗口):

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

或者您使用我创建的帮助文件来避免名为PsRun.exe的窗口。您可以下载源文件和exe文件使用PowerShell中的WinForm GUI运行计划任务。我将它用于计划任务。

编辑:正如Marco所说,这个-windowstyle参数仅适用于V2。

其他提示

您可以使用 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/

(通过 这个论坛主题.)

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

将它放在脚本的前面:

$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.exe 脚本的任务计划程序中的任务,您可以点击<!> 运行用户是否已登录 <!>当任务运行时,它永远不会显示powershell窗口。

在Windows 7上从c#运行时遇到此问题,<!>“交互式服务检测<!>”;运行隐藏的PowerShell窗口作为SYSTEM帐户时弹出服务。

使用<!>“; CreateNoWindow <!>”;参数阻止了ISD服务弹出它的警告。

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

这是一个单行:

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

虽然这可能会非常短暂地闪烁一个窗口,但这应该是罕见的。

我认为在运行后台脚本时隐藏PowerShell控制台屏幕的最佳方法是此代码(<!> quot; 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
  

如果这个答案对您有帮助,请投票给 <> QUOT;!Bluecakes <> QUOT!;在这篇文章的回答中。

我创建了一个小工具,将调用传递给您想要无窗口启动到原始文件的任何控制台工具:

https://github.com/Vittel/RunHiddenConsole

编译后,只需将可执行文件重命名为<!>; <!> lt; targetExecutableName <!> gt; w.exe <!> quot; (附加<!>“w <!>”;),并将其放在原始可执行文件旁边。 然后你可以打电话给e.G. powershellw.exe使用通常的参数,它不会弹出一个窗口。

如果有人知道如何检查创建的进程是否在等待输入,那么很高兴能够包含您的解决方案:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top