如何在使用 -File 选项时隐藏 Powershell 窗口
我像这样调用 Powershell:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1"
我从 python 脚本调用它,但如果通过快捷方式调用,可以观察到相同的问题。我认为 -NonInteractive
标志会导致 Poweshell 在隐藏窗口中执行,但事实并非如此。从外部应用程序调用 Powershell 时是否有办法抑制控制台窗口?
基于 Johannes Rössel 建议的解决方案
import subprocess
st_inf = subprocess.STARTUPINFO()
st_inf.dwFlags = st_inf.dwFlags | subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(["notepad"], startupinfo=st_inf)
I'm calling Powershell like so:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1"
I'm calling it from a python script, but the same problem can be observed if called via a shortcut. I thought the -NonInteractive
flag would cause Poweshell to execute in a hidden window, but it doesn't. Is there a way of supressing the console window when calling Powershell from an external application?
Solution based on Johannes Rössel suggestion
import subprocess
st_inf = subprocess.STARTUPINFO()
st_inf.dwFlags = st_inf.dwFlags | subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(["notepad"], startupinfo=st_inf)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将适当的参数传递给 CreateProcess或 Process.Start 抑制控制台窗口。
但是,PowerShell 还有一个
-WindowStyle
参数,您可以将其设置为隐藏。You can pass appropriate arguments to CreateProcess or Process.Start to suppress the console window.
However, PowerShell also has a
-WindowStyle
parameter which you can set to hidden.我对
-WindowStyle Hidden
没有运气,因为每次都会出现一个控制台窗口一段时间。这就是为什么我使用名为 PsRun.exe 的帮助程序 exe 来完成此操作。您可以下载源代码和exe文件 在 PowerShell 中使用 WinForm GUI 运行计划任务。我用它来执行计划任务。
(请注意,-windowstyle 参数仅适用于 V2。)
I had no luck with
-WindowStyle Hidden
, because a console window appeared every time for a while.That's why I use a helper exe called PsRun.exe that does exactly that. You can download source and exe file Run scheduled tasks with WinForm GUI in PowerShell. I use it for scheduled tasks.
(Note that -windowstyle parameter is available only for V2.)
使用
-WindowStyle Hidden
。请参阅此处。Use
-WindowStyle Hidden
. See here.