首页 > 解决方案 > 隐藏 Powershell 窗口以防止弹出 | VBA

问题描述

我有一个运行 PowerShell 并提交结果的 VBA 脚本。我遇到的问题是 GUI 窗口弹出然后消失。有没有办法在运行时完全隐藏 PowerShell GUI?

这是代码的核心。我添加了 -WindowStyle Hidden,它使 GUI 消失了,但它仍然会闪烁几秒钟然后消失。

Do Until i = LRow + 1

ADGroup = Cells(i, 2)

' Construct PowerShell Command (PS syntax)
strPSCommand = "Get-ADGroupMember -Identity " & ADGroup & " -Recursive |select name"
Debug.Print strPSCommand

' Consruct DOS command to pass PowerShell command (DOS syntax)
strDOSCommand = "powershell -WindowStyle Hidden -command " & strPSCommand & ""

' Create shell object
Set objShell = CreateObject("Wscript.Shell")

' Execute the combined command
Set objExec = objShell.Exec(strDOSCommand)

' Read output into VBS variable
strPSResults = objExec.StdOut.ReadAll

Cells(i, 3).Value = strPSResults

i = i + 1

Loop

标签: excelvbapowershellexcel-2013

解决方案


powershell.exe 是一个控制台应用程序。进程启动时,操作系统会自动创建控制台窗口。因此,处理 -WindowStyle Hidden 的 powershell.exe 代码在控制台窗口打开后执行,因此是 flash。为了解决这个问题,我们需要 wscript 的等价物,即 win32 主机应用程序而不是控制台主机应用程序。


推荐阅读