【发布时间】:2017-03-09 19:26:57
【问题描述】:
我在运行 shell 命令和检查数据输出时遇到了一些问题。如果数据库的当前远程用户处于活动状态,我希望使用 vba 检查。在
命令提示符 =
for /f "tokens=1-8" %a in ('quser') do @if "%d"== "Active" echo %COMPUTERNAME% %a %d
返回登录的用户和他们的状态我希望检查他们没有断开连接(“光盘”)。我使用这个函数来检查 shell 并在消息框中将管道值作为字符串返回
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 命令发出时不返回任何内容。
任何想法都将不胜感激。
【问题讨论】:
-
没关系,while 语句在那里,它就在上一行的末尾,我一定是在论坛的格式中犯了错误。感谢您的评论
-
你让我摸不着头脑,想知道为什么在我插入一段时间后尝试运行它时它没有导致我出现 VBA 语法错误,然后意识到“上一行”是评论,所以它只是忽略了所有额外的陈述 - 呸,我没有崩溃。
-
@YowE3K 我设法弄清楚为什么它不起作用并找到了解决方案。因为 shell 不知道 query.exe(quesr) 的路径,所以它不会继续,因为命令提示符可以使用系统变量来查找 exe。解决方案找到 query.exe 并将其复制到工作目录,然后运行 shell 命令。我的位于 C:\Windows\WinSxS 内的散列文件夹中,请小心,因为这里有 64 位版本和 32 位版本。
标签: vba shell ms-access command-line command