问题描述
我正在尝试使用 Task Scheduler 运行 PowerShell 脚本,它会弹出一个 PowerShell 命令控制台窗口.
I am trying to run a PowerShell script using Task Scheduler and it pops up a PowerShell command console window.
有没有办法在运行脚本时禁用此功能并隐藏窗口?
Is there a way to disable this while running the script and hide the window?
我已经尝试了 -WindowStyle Hidden
但 PowerShell 命令控制台窗口仍然弹出.
I've tried -WindowStyle Hidden
but the PowerShell command console window still pops up.
推荐答案
由于 powershell.exe
是一个控制台程序,如果不显示控制台窗口,您将无法正常执行(虽然您可以隐藏正如您所指出的那样,它在使用 -WindowStyle Hidden
启动后不久.
Since powershell.exe
is a console program, you can't execute it normally without its console window appearing (although you can hide it shortly after it starts by using -WindowStyle Hidden
, as you have noted).
诀窍是在隐藏状态下执行 powershell.exe
本身.一种方法是使用 WshShell 对象的 Run
方法运行隐藏在 WSH 脚本内部的 PowerShell 命令行,并使用 wscript.exe
执行 WSH 脚本(这不是控制台程序,因此不会出现控制台窗口).示例脚本(JScript):
The trick is to execute powershell.exe
itself in a hidden state. One way to do this is by using the WshShell object's Run
method to run a PowerShell command line as hidden from inside a WSH script, and execute the WSH script using wscript.exe
(which is not a console program, so no console window appears). Example script (JScript):
var wshShell = new ActiveXObject("WScript.Shell");
wshShell.Run('%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -File "C:\\Scripts\\My Script.ps1"', 0, false);
如果此脚本是 C:\Scripts\My Launcher.js
,您现在可以运行以下命令行:
If this script is C:\Scripts\My Launcher.js
, you can now run the following command line:
wscript "C:\Scripts\My Launcher.js"
这会在没有控制台的情况下运行启动程序脚本,然后在隐藏窗口中运行 PowerShell 命令(Run
方法的第二个参数是 0
).
This runs the launcher script without a console, which then runs the PowerShell command in a hidden window (the Run
method's second parameter is 0
).
这篇关于在任务计划程序中运行 .ps1 脚本时如何隐藏 PowerShell 窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!