将 shell 命令的输出重定向到文件 [英] Redirect output of shell commands to file

查看:56
本文介绍了将 shell 命令的输出重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从命令提示符运行以下命令

I am running following command from Command Prompt

dir > c:\log.txt 2>&1

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

The out is directed to c:\log.txt file successfully. Then, running the same command using CreateProcessA as below and nothing happens

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

我试过 批处理文件- 如何在 exe 终止后重定向输出?Display &重定向输出

请指出这里有什么问题

推荐答案

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

Why don't you use the shell function? Here is an example of how to redirect the output:

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

这篇关于将 shell 命令的输出重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆