vba shell 命令正在执行但没有输出

vba shell command executing but no output

我在 运行 shell 命令和检查数据输出时遇到了一些问题。如果数据库的当前远程用户处于活动状态,我想使用 vba 检查。在

命令提示符=

for /f "tokens=1-8" %a in ('quser') do @if "%d"== "Active" echo %COMPUTERNAME% %a %d 

returns 已登录的用户及其状态 我希望检查其中 none 个已断开连接 ("Disc")。我使用此函数检查 shell 和 return 管道值作为消息框

中的字符串
Public Function ShellRun(sCmd As String) As String
'Run a shell command, returning the output as a string'

Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")

'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
Debug.Print sCmd

'handle the results as they are written to and read from the StdOut object' 
Dim s As String 
Dim sLine As String 

While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend

ShellRun = s
'example MsgBox ShellRun("cmd.exe /c" & "dir c:\") 
End Function

点击事件调用命令

Dim CMDLineCommand As String 
CMDLineCommand = "for /f ""tokens=1-8"" %a in ('quser') do @if ""%d""== ""Active"" echo %COMPUTERNAME% %a %d" 
'(CMDLineCommand = "dir c:\")<------ THIS WORKS FINE
MsgBox ShellRun("cmd.exe /c " & CMDLineCommand)

这适用于我测试过但不查询的大量命令行命令,因此查询用户。查询用户命令在命令行中运行良好,但在通过 VBA Shell 命令发出时 return 没有任何效果。

如有任何想法,我们将不胜感激。

因为 shell 不知道 query.exe(quesr) 的路径,所以它不会继续,因为命令提示符可以使用系统变量来查找 exe。解决方案找到 query.exe 并将其复制到工作目录,然后 运行 shell 命令。我的位于 C:\Windows\WinSxS 中的散列文件夹中,请小心,因为这里有 64 位版本和 32 位版本。