将shell命令的输出重定向到文件

时间:2013-07-18 07:29:34

标签: shell winapi command-line vb6 cmd

我正在从命令提示符

运行以下命令
dir > c:\log.txt 2>&1

out成功定向到c:\log.txt文件。 然后,使用CreateProcessA运行相同的命令,如下所示,没有任何反应

Public Function ExecCmd(cmdline$)
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO
Dim ret As Long

start.cb = Len(start)
start.dwFlags = 1
start.wShowWindow = 1
ret& = CreateProcessA(vbNullString, cmdline$, 0&, 0&, 1&, NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)
ret = WaitForSingleObject(proc.hProcess, INFINITE)
Call GetExitCodeProcess(proc.hProcess, ret&)
Call CloseHandle(proc.hThread)
Call CloseHandle(proc.hProcess)
ExecCmd = ret&
End Function

此处cmdline$传递为dir > c:\log.txt 2>&1

我已尝试Batch file - How to redirect output from exe after it has terminated?Display & Redirect Output

请说明这里有什么问题

1 个答案:

答案 0 :(得分:1)

为什么不使用shell功能?以下是如何重定向输出的示例:

Option Explicit

Private Sub Form_Load()
    ExecCmd "dir >c:\log.txt 2>&1"
End Sub

Private Sub ExecCmd(cmdline As String)
    Shell "cmd /c " & cmdline, vbHide
End Sub