windows 如何在不显示窗口的情况下运行 PowerShell 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1802127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:57:01  来源:igfitidea点击:

How to run a PowerShell script without displaying a window?

windowspowershellscriptingbatch-filesilent

提问by Thomas Bratt

How is it possible to run a PowerShellscript without displaying a window or any other sign to the user?

如何在不向用户显示窗口或任何其他标志的情况下运行PowerShell脚本?

In other words, the script should run quietly in the background without any sign to the user.

换句话说,脚本应该在后台安静地运行,而不会给用户任何迹象。

Extra credit for an answer that does not use third party components :)

不使用第三方组件的答案的额外功劳:)

采纳答案by stej

You can either run it like this (but this shows a windows for a while):

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

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

Or you use a helper file I created to avoid the window 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.

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

Edited: as Marco noted this -windowstyle parameter is available only for V2.

编辑:正如 Marco 指出的,此 -windowstyle 参数仅适用于 V2。

回答by Yusha

I was having this same issue. I found out if you go to the Taskin Task Schedulerthat is running the powershell.exescript, you can click "Run whether user is logged on or not" and that will never show the powershell window when the task runs.

我遇到了同样的问题。我发现,如果你去的任务任务计划程序运行的powershell.exe脚本,你可以点击“运行用户是否登录或不”,而且绝不会显示PowerShell窗口在任务运行时。

回答by ax.

You can use the PowerShell Community Extensionsand do this:

您可以使用PowerShell 社区扩展并执行以下操作:

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

You can also do this with VBScript: http://blog.sapien.com/index.php/2006/12/26/more-fun-with-scheduled-powershell/

您也可以使用 VBScript 执行此操作:http: //blog.sapien.com/index.php/2006/12/26/more-fun-with-scheduled-powershell/

(Via this forum thread.)

(通过这个论坛帖子。)

回答by Andy Lowry

Here's an approach that that doesn't require command line args or a separate launcher. It's not completely invisible because a window does show momentarily at startup. But it then quickly vanishes. Where that's OK, this is, I think, the easiest approach if you want to launch your script by double-clicking in explorer, or via a Start menu shortcut (including, of course the Startup submenu). And I like that it's part of the code of the script itself, not something external.

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

Put this at the front of your script:

把它放在你的脚本的前面:

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

回答by Adam Taylor

Here's a one-liner:

这是一个单行:

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

Although it's possible for this to flash a window very briefly, that should be a rare occurrence.

尽管这可能会非常短暂地闪烁一个窗口,但这种情况应该很少发生。

回答by jmc

I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.

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

Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.

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

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

回答by gavraham

I think that the best way to hide the console screen of the PowerShell when your are running a background scripts is this code("Bluecakes" answer).

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

I add this code in the beginning of all my PowerShell scripts that I need to run in background.

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

If this answer was help you, please vote to "Bluecakes" in his answer in this post.

如果这个答案对你有帮助,请在他在这篇文章的回答中投票给“Bluecakes”。

回答by Garric

ps1 hidden from the Task Scheduler and shortcut too

ps1 也隐藏在任务计划程序和快捷方式中

    mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""powershell -ExecutionPolicy Bypass & 'C:\PATH\NAME.ps1'"", 0:close")

回答by Chris

I have created a small tool passing the call to any console tool you want to start windowless through to the original file:

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

https://github.com/Vittel/RunHiddenConsole

https://github.com/Vittel/RunHiddenConsole

After compiling just rename the executable to "<targetExecutableName>w.exe" (append a "w"), and put it next to the original executable. You can then call e.G. powershellw.exe with the usual parameters and it wont pop up a window.

编译后只需将可执行文件重命名为“<targetExecutableName>w.exe”(附加“w”),并将其放在原始可执行文件旁边。然后,您可以使用常用参数调用 eG powershellw.exe,它不会弹出窗口。

If someone has an idea how to check whether the created process is waiting for input, ill be happy to include your solution :)

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

回答by js2010

Here's a fun demo of controlling the various states of the console, including minimize and hidden.

这是控制控制台各种状态的有趣演示,包括最小化和隐藏。

Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
   [DllImport("Kernel32.dll")]
   public static extern IntPtr GetConsoleWindow();
   [DllImport("user32.dll")]
   public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'@

$ConsoleMode = @{
 HIDDEN = 0;
 NORMAL = 1;
 MINIMIZED = 2;
 MAXIMIZED = 3;
 SHOW = 5
 RESTORE = 9
 }

$hWnd = [WPIA.ConsoleUtils]::GetConsoleWindow()

$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MAXIMIZED)
"maximized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.NORMAL)
"normal $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MINIMIZED)
"minimized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.RESTORE)
"restore $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.HIDDEN)
"hidden $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.SHOW)
"show $a"