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

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

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


当前回答

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

https://github.com/Vittel/RunHiddenConsole

编译完成后,只需将可执行文件重命名为“<targetExecutableName>w.exe”(附加一个“w”),并将其放在原始可执行文件旁边。 然后你可以用通常的参数调用e.G. powershell .exe,它不会弹出一个窗口。

如果有人知道如何检查创建的进程是否等待输入,我会很高兴包括你的解决方案:)

其他回答

您可以使用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(互联网档案)

(通过这个论坛。)

我从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
};

下面是一行代码:

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

虽然这可能会让窗口非常短暂地闪现,但这种情况应该很少发生。

我真的厌倦了通过答案,却发现它没有像预期的那样工作。

解决方案

创建vbs脚本运行一个隐藏的批处理文件,该文件将启动powershell脚本。为这个任务制作3个文件似乎很愚蠢,但至少总大小小于2KB,它从任务器或手动运行完美(你看不到任何东西)。

scriptName.vbs

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Users\leathan\Documents\scriptName.bat" & Chr(34), 0
Set WinScriptHost = Nothing

scriptName.bat

powershell.exe -ExecutionPolicy Bypass C:\Users\leathan\Documents\scriptName.ps1

scriptName.ps1

Your magical code here.
powershell.exe -windowstyle hidden -noexit -ExecutionPolicy Bypass -File <path_to_file>

然后设置运行:最小化

应该像预期的那样工作,而没有添加隐藏窗口闪光的代码 只是稍微延迟了一点。